react 組件的構造函數


constructor 函數時組件最先執行的函數

class childen extends react.Component{
   constructor(props){
      super(props);
      this.state={
          attr1:"",
      }
  }
}

一般在constructor函數中都會存在 上述方法,個人對其的理解

constructor():子類繼承父類時的構造方法,主要時用以定義this.屬性 在react中一些默認的數據可以直接在此處定義

import React from 'react';

class Mine extends React.Component {
    constructor(a) {
        super(a);
        this.state = {
            date: new Date().getTime()
        }
        //定義custom 和state並沒有什么本質的區別,在都可以通過this都訪問,但是推薦使用state 因為在react中 即使我們不定義this.state
        //this下仍會有一個默認的state屬性,具體作用暫時沒有發現,感興趣的同學可以深入了解一下
        this.custom = {
            date: new Date().getTime()
        }
        console.log(a);
    }

    componentWillMount() {
        console.log("在渲染前調用",this)
    }

    render() {
        return (
            <div>
                <div className='head'>
                    <span>{this.state.date}</span>
                   <span>{this.custom.date}</span>
                </div>
            </div>
        )
    }
}

 

spuer(): 注意在定義組件的時候可以沒用constructor方法,一旦定義,就必須使用spuer方法,這不是react規定的而是es6要求,具體原因如下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM