react中可以使用super;react中定義的構造函數(shù)必須要調用super()對父類進行初始化,super()可以調用了父類的構造函數(shù)來去實例化子類本身,如果在constructor中要使用“this.props”,就必須給super加參數(shù),語法為“super(props)”。

本教程操作環(huán)境:Windows10系統(tǒng)、react17.0.1版、Dell G3電腦。
react中使用super
在學習react的時候,其中在構造函數(shù)里面,有一個super(props),具體是什么意思呢。
其中 super語法來自es6,其語法如下:
super([arguments]); // 調用 父對象/父類 的構造函數(shù) super.functionOnParent([arguments]); // 調用 父對象/父類 上的方法
我們要理解react中的super(props),,就先看一下,es6的構造函數(shù)constructor
看如下js
class Person{ constructor(props){ console.log("參數(shù):"+props); console.log("初始化 Person constructor"); this.name = "Person"; } } class Child extends Person{ getName(){ console.log("名字為:"+this.name); } } var child = new Child(); child.getName();
在js中,類在 new 實例化的時候,系統(tǒng)會默認調用constructor函數(shù),在 Child類中,我們沒有定義構造函數(shù),那個系統(tǒng)會默認有一個constructor,并且會在里面調用super(); 當我們定義了構造函數(shù)之后,就使用我們定義的。所以我們自己定義的構造函數(shù)必須要調用super()對父類進行初始化。
在react中,如果不需要在 constructor里面使用 props,是可以不用寫 constructor的


這個兩種調用和不調用的區(qū)別,
1、如果不需要 在 constructor里面使用 this.props ,是可以不用給super傳props的
2、如果不要在constructor寫邏輯,僅僅是寫一個super(props),實際上整個constructor都沒有寫的必要
3、目前react支持一種新的寫法,沒有constructor情況下面的初始化數(shù)據(jù),非常方便

【
站長資訊網(wǎng)