function FormattedDate(props) {
return
当前:{props.date.toLocaleDateString()}
{props.date.toLocaleTimeString()}
;
}
export default class Datetime extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
// 组件挂载完成之后启动定时器
componentDidMount() {
this.timeID = setInterval(() => this.tick(), 1000);
}
// 组件卸载之前清除定时器
//(注:这是我们用这个钩子函数经常做的一件事)
componentWillUnmount() {
clearInterval(this.timeID);
}
// 定义一个tick方法,专门用于调用setState方法修改date
tick() {
this.setState({
date: new Date(),
});
}
render() {
const { className }=this.props;
return (
);
}
}