react moment如何使用
安装 react-moment
通过 npm 或 yarn 安装 react-moment 包:
npm install react-moment moment
或
yarn add react-moment moment
基本用法
在 React 组件中导入并使用 Moment 组件来格式化日期:
import React from 'react';
import Moment from 'react-moment';
function App() {
return (
<div>
<Moment>{new Date()}</Moment>
</div>
);
}
格式化日期
使用 format 属性自定义日期格式:
<Moment format="YYYY-MM-DD HH:mm:ss">{new Date()}</Moment>
相对时间
显示相对时间(如“几秒前”或“几天前”):
<Moment fromNow>{new Date()}</Moment>
本地化
结合 moment 的本地化功能显示本地化时间:
import moment from 'moment';
import 'moment/locale/zh-cn'; // 导入中文语言包
moment.locale('zh-cn'); // 设置为中文
<Moment locale="zh-cn" fromNow>{new Date()}</Moment>
时间间隔
使用 duration 属性显示时间间隔:
<Moment duration={new Date()} date={new Date(Date.now() - 1000 * 60 * 60)} />
时区转换
使用 tz 属性转换时区:
<Moment tz="America/New_York" format="YYYY-MM-DD HH:mm:ss">
{new Date()}
</Moment>
自定义输出
使用 withTitle 属性添加 title 提示:

<Moment withTitle format="YYYY-MM-DD HH:mm:ss">
{new Date()}
</Moment>
注意事项
react-moment依赖于moment库,确保同时安装moment。- 频繁更新时间的组件可能需要优化性能,避免不必要的重渲染。
- 对于国际化项目,需手动导入并设置对应的语言包。
通过以上方法,可以灵活使用 react-moment 处理日期和时间显示需求。






