6.React状态以及生命周期

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>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

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

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/javascript/react/9700.html

(0)
上一篇 2021年11月5日 02:00
下一篇 2021年11月7日 02:45

相关推荐

  • 4.React元素(JS 对象)的介绍

    这个对象被称为 “React 元素”。它们描述了你希望在屏幕上看到的内容。React 通过读取这些对象,然后使用它们来构建 DOM 以及保持随时更新。

    React教程 2021年11月4日
    04200
  • 1.使用React的两种方式

    1.直接添加到网站的方式 index.html like_button.js 压缩 like_button.js 代码 确保计算机已安装Node.js,然后在项目文件夹下运行如下命令: 安装 JSX 预处理器(Babel) 以下这两段代码是等价的。 若想支持JSX,需要安装 JSX 预处理器(Babel)。确保计算机已…

    React教程 2021年11月1日
    06360
  • 2.React元素渲染的流程

    1.创建DOM容器 2.创建React元素 2.1创建JSX 2.2JSX自动转换为浏览器原生支持 2.3浏览器原生支持转换为React元素(JS对象) 3.渲染React元素

    React教程 2021年11月2日
    04020

发表回复

登录后才能评论