zoukankan      html  css  js  c++  java
  • React State 状态

    React 把组件看成是一个状态机(State Machines)。通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。

    React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。

    以下实例创建一个名称扩展为 React.Component 的 ES6 类,在 render() 方法中使用 this.state 来修改当前的时间。

    添加一个类构造函数来初始化状态 this.state,类组件应始终使用 props 调用基础构造函数。

    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {date: new Date()};
      }
    
      componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
    
      componentWillUnmount() {
        clearInterval(this.timerID);
      }
    
      tick() {
        this.setState({
          date: new Date()
        });
      }
    
      render() {
        return (
          <div>
            <h1>Hello, world!</h1>
            <h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
          </div>
        );
      }
    }
    
    ReactDOM.render(
      <Clock />,
      document.getElementById('example')
    );
    
  • 相关阅读:
    PHP调试总结
    vim常用命令
    Xshell
    JavaScript
    HTML+CSS
    解决VMware“该虚拟机似乎正在使用中”问题
    MVC dirname(——FILE——)
    各种编程语言中的指针和引用
    Go defer 原理和源码剖析
    软件架构定义的流派
  • 原文地址:https://www.cnblogs.com/heson/p/12011136.html
Copyright © 2011-2022 走看看