react中可以使用super;react中定義的構(gòu)造函數(shù)必須要調(diào)用super()對父類進(jìn)行初始化,super()可以調(diào)用了父類的構(gòu)造函數(shù)來去實(shí)例化子類本身,如果在constructor中要使用“this.props”,就必須給super加參數(shù),語法為“super(props)”。
本教程操作環(huán)境:Windows10系統(tǒng)、react17.0.1版、Dell G3電腦。
react中使用super
在學(xué)習(xí)react的時(shí)候,其中在構(gòu)造函數(shù)里面,有一個(gè)super(props),具體是什么意思呢。
其中 super語法來自es6,其語法如下:
super([arguments]); // 調(diào)用 父對象/父類 的構(gòu)造函數(shù) super.functionOnParent([arguments]); // 調(diào)用 父對象/父類 上的方法
我們要理解react中的super(props),,就先看一下,es6的構(gòu)造函數(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 實(shí)例化的時(shí)候,系統(tǒng)會默認(rèn)調(diào)用constructor函數(shù),在 Child類中,我們沒有定義構(gòu)造函數(shù),那個(gè)系統(tǒng)會默認(rèn)有一個(gè)constructor,并且會在里面調(diào)用super(); 當(dāng)我們定義了構(gòu)造函數(shù)之后,就使用我們定義的。所以我們自己定義的構(gòu)造函數(shù)必須要調(diào)用super()對父類進(jìn)行初始化。
在react中,如果不需要在 constructor里面使用 props,是可以不用寫 constructor的
這個(gè)兩種調(diào)用和不調(diào)用的區(qū)別,
1、如果不需要 在 constructor里面使用 this.props ,是可以不用給super傳props的
2、如果不要在constructor寫邏輯,僅僅是寫一個(gè)super(props),實(shí)際上整個(gè)constructor都沒有寫的必要
3、目前react支持一種新的寫法,沒有constructor情況下面的初始化數(shù)據(jù),非常方便
【