javascript、react——setInterval方法,react的componentDidMount生命周期方法

1.代码

  <body>
    <div id="test"></div>

    <script type="text/babel">
      "use strict";

      class Life extends React.Component {
    
    
        state = {
    
     opacity: 1 };

        death = () => {
    
    
          clearInterval(this.timer);
          ReactDOM.unmountComponentAtNode(document.getElementById("test"));
        };

        componentDidMount() {
    
    
          this.timer = setInterval(() => {
    
    
            let {
    
     opacity } = this.state;
            opacity -= 0.1;
            if (opacity <= 0) opacity = 1;
            this.setState({
    
     opacity });
          }, 200);
        }

        render() {
    
    
          console.log("render");
          return (
            <div>
              <h2 style={
    
    {
    
     opacity: this.state.opacity }}>字段</h2>
              <button onClick={
    
    this.death}>卸载该组件</button>
            </div>
          );
        }
      }
      ReactDOM.render(<Life />, document.getElementById("test"));
    </script>
  </body>

2.代码讲解

  1. serInterval方法有两个参数,第一个参数是一个方法,第二个参数是一个毫秒值。serInterval方法的作用是重复执行第一个参数方法,间隔第二个参数的毫秒时间。
  2. componentDidMount方法是当render执行后,自动执行的一个生命周期方法
  3. serInterval使用后需要记得清除它,clearInterval(this.timer);该方法用于清除定时器,参数为要清除的目标定时器

3.运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45895576/article/details/113599585