React 组件封装:获取当前时间并计算指定秒数后的时间
以下是一个简单的 React 组件,它接受一个名为'seconds'的整数属性,然后在组件的 state 中计算出当前时间和秒数后的时间,并将其呈现为字符串:
import React, { Component } from 'react';
class TimeDisplay extends Component {
constructor(props) {
super(props);
this.state = { currentTime: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
currentTime: new Date()
});
}
formatTime(seconds) {
const endTime = new Date(this.state.currentTime.getTime() + seconds * 1000);
return `${endTime.toLocaleTimeString()}`;
}
render() {
const { seconds } = this.props;
const endTime = this.formatTime(seconds);
return (
<div>
<p>Current Time: {this.state.currentTime.toLocaleTimeString()}</p>
<p>{seconds} seconds from now: {endTime}</p>
</div>
);
}
}
export default TimeDisplay;
在这个组件中,我们使用了 React 的生命周期方法来设置一个计时器,以便每秒钟更新当前时间。我们还定义了一个名为'formatTime'的辅助方法,该方法接受一个名为'seconds'的参数,并返回当前时间加上该秒数后的时间的字符串表示。我们在 render 方法中使用这个辅助方法来呈现我们的输出。
原文地址: https://www.cveoy.top/t/topic/n9Qi 著作权归作者所有。请勿转载和采集!