React組件的生命周期(三)

react-lifecycle.png

start -> getDefaultprops -> getInitialState
componentWillMount :當(dāng)組件即將渲染的時(shí)候觸發(fā)的函數(shù)
componentDidMount:當(dāng)組件渲染完成觸發(fā)的一個(gè)函數(shù)
componentWillUpdate:當(dāng)組件發(fā)生改變的時(shí)候觸發(fā)
componentDidUpdate:當(dāng)組件發(fā)生改變的時(shí)候觸發(fā)
componentWillUnmount:組件被卸載的時(shí)候觸發(fā)

componentWillReceiveProps:props改變之前
shouldComponentUpdate:props改變之后

 var HelloReact = React.createClass({
      getDefaultprops:function(){
        console.log("getDefaultprops");
      },
      // getInitialState:function(){
      //   console.log("getInitialState");
      // },
      componentWillMount:function(){
        console.log("componentWillMount");
      },
      componentDidMount:function(){
        console.log("componentDidMount");
      },
      render:function(){
        return(
          <div>我是Hello React</div>
        )
      }
   })
 ReactDOM.render(<HelloReact />,document.getElementById("root"));

例子;使背景顏色的透明度慢慢變化

 // css
<style>
    .div{
      width:100px;
      height: 100px;
      background-color: red;
    }
</style>

1.state:狀態(tài) 當(dāng)組件自身改變的內(nèi)容,可以使用state處理
1.this.state :獲取
2.this.setState :設(shè)置
2.當(dāng)state改變的時(shí)候,會(huì)觸發(fā)render重新渲染
區(qū)分:props外部組件傳遞的一些值;state組件內(nèi)部改變觸發(fā)的狀態(tài)

//js and HTML
  <body>
     <div id="root"></div>
     <script type="text/babel">
         var ComState = React.createClass({
      //初始化state
         getInitialState:function(){
            return{
                 opacity:1.0
            }
         },

         componentDidMount:function(){
            var timer = setInterval(function(){
            var opacitys = this.state.opacity;
            opacitys-=0.02;
            this.setState({
                   opacity:opacitys
             })
            }.bind(this),100)   //在間隔調(diào)用里this指向window,所以要改變this指向
         },            //call-對(duì)象;apply-數(shù)組;bind

         componentWillUpdate:function(){
            console.log("componentWillUpdate");
            },
         componentDidUpdate:function(){
           console.log("componentDidUpdate");
            },
         render:function () {
           return(
               <div className="div" style={{opacity:this.state.opacity}}>{this.props.title}</div>
           )
         }
    })

    ReactDOM.render(<ComState title="nihaome" />,document.getElementById("root"));
  </script>
</body>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容