在React中获取当前日期的方法有多种方式:
const currentDate = new Date();
console.log(currentDate);
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [currentDate, setCurrentDate] = useState('');
useEffect(() => {
const date = new Date();
setCurrentDate(date);
}, []);
return (
<div>
<p>{currentDate.toString()}</p>
</div>
);
};
export default MyComponent;
安装Moment.js并导入它:
npm install moment
使用Moment.js来获取当前日期:
import React from 'react';
import moment from 'moment';
const MyComponent = () => {
const currentDate = moment().format('YYYY-MM-DD');
return (
<div>
<p>{currentDate}</p>
</div>
);
};
export default MyComponent;