React中,通过改变组件的状态来改变页面的内容

  React框架有一个特性,当React检测到页面内容有变化是,它会自动刷新页面,并且自动更新页面中需要更新的部分。但是React并不会把更新的内容挂在真是的DOM上,因此我们单单对页面数据或者组件改动是,并不会看到页面有任何变化。React提供了组件的一个私有的,其他任何组件没有权限改变的属性:state(状态)。我们可以通过ES6的类定义一个组件: (访问上一个组件的状态可用prevState获取)

  

class Clock extends React.Component{
  constructor(props) {
    super(props);
    this.state = {date: new Date()}
  }

};

在组件的构造函数中,我们定义了一个组件状态的一个属性:date,当组件内容需要变化是,我们改变state的对应的值就可以了。这里我们每过一秒更新一次显示的时间,那么我们就每过一秒跟新一次this.state的date的值。代码如下:

  

class Clock extends React.Component{
  constructor(props) {
    super(props);
    this.state = {date: new Date()}
  }

  componentDidMount() { //组件渲染完成,要挂载到页面前执行的代码
    this.timer = setInterval(
      () => this.trick(),
      1000
    );
  }

  componentWillUnmount() { //组件从页面卸载前执行的方法
    clearInterval(this.timer);
  }

  trick() {
    this.setState({date: new Date()}); //改变组件的状态
  }

  render() {
    return (
      <div>
        <h1>Hello World!</h1>
        <h2>{this.state.date.toLocaleTimeString()}</h2>
      </div>
    );
  }
};

ReactDOM.render(
  <Clock/>,
  document.getElementById('main')
);

这样,页面会显示一个精确到秒的电子表啦!

原文地址:https://www.cnblogs.com/zhangbob/p/6955476.html