react中constructor和super

在react中組件中我們一般會(huì)寫(xiě)一下代碼

constructor(props) {
  super(props);
  // some code
}

1.我們是否可以不用在自雷中寫(xiě)constructor,不寫(xiě)construction也是可以的,但是要看在那些場(chǎng)景下

class HelloWord extends React.Component{
}
// 等價(jià)于
class HelloWord extends React.Component{
    construction(...args){
        super(..args)
    }
}

如果子類沒(méi)有定義constructor方法,這個(gè)方法會(huì)被默認(rèn)添加。也就是說(shuō),不管有沒(méi)有顯式定義,任何一個(gè)子類都有constructor方法,所以在一些特定的環(huán)境下是可以省略的。比如下面這個(gè)例子

class ErrorCatch extends React.Component {

  handleClick = () => {
    console.log('hello world');
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>點(diǎn)擊</button>
      </div>
    );
  }
}
export default ErrorCatch;

2.如果顯示定義了constructor,那么就必須在constructor函數(shù)里面調(diào)用super(),比如

class Person {
    constructor(name){
        this.name = name
    }
}
class MaySir extends Person{
    constructor(){
        super()
    }
    print() {
        console.log("實(shí)例化個(gè)人");
    }
}

如果只是顯示的定義了constructor,而不調(diào)用super(),那么實(shí)例化就會(huì)失敗,比如只定義了constructor,而不調(diào)用super()

class Person {
    constructor(name){
        this.name = name
    }
}
class MaySir extends Person{
    constructor(){
        // super()
    }
    print() {
        console.log("實(shí)例化個(gè)人");
    }
}
const man = new MaySir().print()
image.png

報(bào)錯(cuò)的原因是:子類中是沒(méi)有自己的this對(duì)象的,它的this對(duì)象只能夠繼承父類的this對(duì)象,然后對(duì)其加工包裝,而super()就是相當(dāng)于把父類的中this對(duì)象過(guò)繼給子類。如果沒(méi)有調(diào)用super(),那么子類也就不能夠使用this對(duì)象了。class繼承類(extends)如果顯示的定義了constructor必須要調(diào)用super(),如果不是extends繼承類可以不用調(diào)用super().注:并且要把super()調(diào)用放在最前面執(zhí)行。
3. 在react中是否需要寫(xiě)super(props),如果在子組件中使用了props就需要調(diào)用super(props),否則在子組件中使用this.props會(huì)報(bào)錯(cuò),如果在子組件中不使用this.props,則直接調(diào)用super()即可

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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