1. 程式人生 > >為什麽react的組件要super(props)

為什麽react的組件要super(props)

ebo comment html ocs user data- font 初始化 created

為什麽react的組件要super(props)

摘自 https://segmentfault.com/q/1010000008340434 (非原創)

技術分享

如圖,我知道supert是繼承constructor的參數,但是為什麽在react裏面,有一些組件使用了super(props),而有一些沒有寫,還有在es6裏就只是寫了supert(),這些區別在哪呢?以及這裏的這個constructor(props)...super(props)是起到什麽作用呢

這個是全代碼:

技術分享

已采納
  1. 調用super的原因:在ES6中,在子類的constructor中必須先調用super

    才能引用this

  2. super(props)的目的:在constructor中可以使用this.props

  3. 最後,可以看下React文檔,裏面有一段

Class components should always call the base constructor with props.

zhangfe1k 聲望

原來如此,謝謝了。

any · 2月14日

1

根本原因是constructor會覆蓋父類的constructor,導致你父類構造函數沒執行,所以手動執行下。

brook · 2月18日

假設在es5要實現繼承,首先定義一個父類:

//父類
function sup(name) {
    this.name = name
}
//定義父類原型上的方法
sup.prototype.printName = function (){
    console.log(this.name)
}

現在再定義他sup的子類,繼承sup的屬性和方法:

function sub(name,age){
    sup.call(this,name)    //調用call方法,繼承sup超類屬性
    this.age = age
}    

sub.prototype = new sup   //把子類sub的原型對象指向父類的實例化對象,這樣即可以繼承父類sup原型對象上的屬性和方法
sub.prototype.constructor = sub    //這時會有個問題子類的constructor屬性會指向sup,手動把constructor屬性指向子類sub
//這時就可以在父類的基礎上添加屬性和方法了
sub.prototype.printAge = function (){
    console.log(this.age)
}

這時調用父類生成一個實例化對象:

    let jack = new sub(‘jack‘,20)
    jack.printName()    //輸出 : jack
    jack.printAge()    //輸出 : 20

這就是es5中實現繼承的方法。
而在es6中實現繼承:

    class sup {
        constructor(name) {
            this.name = name
        }
    
        printName() {
            console.log(this.name)
        }
    }


class sub extends sup{
    constructor(name,age) {
        super(name)
        this.age = age
    }

    printAge() {
        console.log(this.age)
    }
}

let jack = new sub(‘jack‘,20)
    jack.printName()    //輸出 : jack
    jack.printAge()    //輸出 : 20

對比es5和es6可以發現在es5實現繼承,在es5中實現繼承:

  1. 首先得先調用函數的call方法把父類的屬性給繼承過來

  2. 通過new關鍵字繼承父類原型的對象上的方法和屬性

  3. 最後再通過手動指定constructor屬性指向子類對象

而在es6中實現繼承,直接調用super(name),就可以直接繼承父類的屬性和方法,所以super作用就相當於上述的實現繼承的步驟,不過es6提供了super語法糖,簡單化了繼承的實現

yuchav · 7月29日

為什麽最後再通過手動指定constructor屬性指向子類對象

happyhuizai · 1 天前

如果你用到了constructor就必須寫super(),是用來初始化this的,可以綁定事件到this上;
如果你在constructor中要使用this.props,就必須給super加參數:super(props)
(無論有沒有constructor,在renderthis.props都是可以使用的,這是React自動附帶的;)
如果沒用到constructor,是可以不寫的,直接:

class HelloMessage extends React.Component{
    render (){
        return (
            <div>nice to meet you! {this.props.name}</div>
        );
    }
}
//不過這種只是用render的情況,使用一般的ES6函數寫會更簡便:
const HelloMessage = (props)=>(
    <div>nice to meet you! {this.props.name}</div>
)

為什麽react的組件要super(props)