其他分享
首页 > 其他分享> > react生命周期

react生命周期

作者:互联网

-

生命周期回调函数----生命周期钩子函数-----生命周期函数

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>引出生命周期.</title>
</head>
<body>
  <!-- 准备一个容器 -->
  <div id="test"></div>
  <!-- 引入react核心库 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
  <!-- 引入react-dom, 用于支持react操作dom, 需要在核心库之后引入 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
  <!-- 引入babel.js,用于将jsx转化为js -->
  <script src="https://cdn.bootcdn.net/ajax/libs/babel-standalone/7.18.7/babel.min.js"></script>
  <!-- 引入prop-types -->
  <script src="https://cdn.bootcdn.net/ajax/libs/prop-types/15.8.1/prop-types.min.js"></script>
  <script type="text/babel">
    class Life extends React.Component {
      state = { opacity: 0 };

      death = () => {
        // 卸载组件
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
      }

      // 组件挂载完毕
      componentDidMount() {
        this.timer = setInterval(() => {
          let { opacity } = this.state;
          opacity -= 0.1;
          console.log(opacity, 'opacity===');
          if(opacity <= 0) opacity = 1;
          this.setState({ opacity })
        }, 200);
      }
      // 组件即将卸载
      componentWillUnmount() {
        clearInterval(this.timer)
      }

      render() {
        return (
          <div>
            <h2 style={{ opacity: this.state.opacity }}>react学不会怎么办?</h2>
            <button onClick={this.death}>不活了</button>
          </div>
        )
      }
    }
    ReactDOM.render(<Life />, document.getElementById('test'))
  </script>
</body>
</html>

 

 

 

 

-

标签:opacity,生命周期,react,state,test,document,ReactDOM
来源: https://www.cnblogs.com/fqh123/p/16648121.html