【React一】React基础+组件化编程【ref+props+state】
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
import React, { Component } from 'react';
class Clock extends Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default Clock;
这段代码展示了如何在React组件中使用state来管理时间,并在组件挂载(mount)和卸载(unmount)时处理定时器的创建和清除。这是学习React组件化编程的一个基本例子。
评论已关闭