0%

802_React_引出生命周期

<script type="text/babel">
      //生命周期回调函数 <=> 生命周期钩子函数
      class Life extends React.Component {
        state = { opacity: 1 };
        death = () => {
          //卸载组件
          ReactDOM.unmountComponentAtNode(document.getElementById("test"));
        };

        //组件卸载之前清除定时器
        componentWillUnmount() {
          clearInterval(this.timer);
        }

        //组件挂载完毕后调用
        componentDidMount() {
          this.timer = setInterval(() => {
            //获取原来的状态
            let { opacity } = this.state;
            //减小0.1
            opacity -= 0.1;
            if (opacity <= 0) opacity = 1;
            //设置新的透明度
            this.setState({ opacity: opacity });
          }, 200);
        }

        //初次渲染和页面更新时调用
        render() {
          return (
            <div>
              <h2 style={{ opacity: this.state.opacity }}>React学不会怎么办</h2>
              <button onClick={this.death}>不活了</button>
            </div>
          );
        }
      }
      //2、渲染虚拟DOM到页面
      ReactDOM.render(<Life />, document.querySelector("#test"));
    </script>