React框架有一个特性,当React检测到页面内容有变化是,它会自动刷新页面,而且自动更新页面中须要更新的部分。可是React并不会把更新的内容挂在真是的DOM上,所以咱们单单对页面数据或者组件改动是,并不会看到页面有任何变化。React提供了组件的一个私有的,其余任何组件没有权限改变的属性:state(状态)。咱们能够经过ES6的类定义一个组件: (访问上一个组件的状态可用prevState获取)框架
class Clock extends React.Component{
constructor(props) {
super(props);
this.state = {date: new Date()}
}函数
};this
在组件的构造函数中,咱们定义了一个组件状态的一个属性:date,当组件内容须要变化是,咱们改变state的对应的值就能够了。这里咱们每过一秒更新一次显示的时间,那么咱们就每过一秒跟新一次this.state的date的值。代码以下:spa
class Clock extends React.Component{
constructor(props) {
super(props);
this.state = {date: new Date()}
}component
componentDidMount() { //组件渲染完成,要挂载到页面前执行的代码
this.timer = setInterval(
() => this.trick(),
1000
);
}get
componentWillUnmount() { //组件从页面卸载前执行的方法
clearInterval(this.timer);
}class
trick() {
this.setState({date: new Date()}); //改变组件的状态
}渲染
render() {
return (
<div>
<h1>Hello World!</h1>
<h2>{this.state.date.toLocaleTimeString()}</h2>
</div>
);
}
};date
ReactDOM.render(
<Clock/>,
document.getElementById('main')
);
这样,页面会显示一个精确到秒的电子表啦!权限