使用react实现时钟
使用 React 实现时钟
方法一:使用 useState 和 useEffect 实现动态时钟
import React, { useState, useEffect } from 'react';
function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const timerID = setInterval(() => {
setTime(new Date());
}, 1000);
return () => {
clearInterval(timerID);
};
}, []);
return (
<div>
<h1>当前时间:</h1>
<h2>{time.toLocaleTimeString()}</h2>
</div>
);
}
export default Clock;
方法二:使用类组件实现时钟
import React from 'react';
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { time: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
time: new Date()
});
}
render() {
return (
<div>
<h1>当前时间:</h1>
<h2>{this.state.time.toLocaleTimeString()}</h2>
</div>
);
}
}
export default Clock;
方法三:自定义格式显示时间
function formatTime(date) {
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
return `${hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
}
// 在以上任一组件中使用
function Clock() {
// ...
return (
<div>
<h1>自定义格式时间:</h1>
<h2>{formatTime(time)}</h2>
</div>
);
}
方法四:添加日期显示
function Clock() {
// ...
return (
<div>
<h1>当前日期和时间:</h1>
<h2>{time.toLocaleDateString()} {time.toLocaleTimeString()}</h2>
</div>
);
}
方法五:使用第三方库(如 moment.js)
import moment from 'moment';
function Clock() {
const [time, setTime] = useState(moment());
useEffect(() => {
const timerID = setInterval(() => {
setTime(moment());
}, 1000);
return () => clearInterval(timerID);
}, []);
return (
<div>
<h1>Moment.js 格式:</h1>
<h2>{time.format('YYYY-MM-DD HH:mm:ss')}</h2>
</div>
);
}

