React中super()和super(props)的區(qū)別小結(jié)
1. ES6類
在ES6中,通過extends關(guān)鍵字實現(xiàn)類的繼承,方式如下:
class sup{
constructor(name){
this.name=name;
}
printName(){
console.log(this.name)
}
}
class sub extends sup{
constructor(name,age){
super(name) //super 代表的是父類的構(gòu)造函數(shù)
this.age=age;
}
printAge(){
console.log(this.age)
}
}
let rui=new sub('rui',21);
rui.printAge() //21
rui.printName() //rui
在上面的例子在子中,可以看到通過super關(guān)鍵字實現(xiàn)調(diào)用父類,super代替的是父類的構(gòu)建函數(shù),使用super(name)相當(dāng)于調(diào)sup.prototype.constructor.call(this.name)
如果在子類中不使用super關(guān)鍵字,則會引發(fā)報錯
報錯的原因是 子類沒有自己的this對象,它只能繼承父類的this對象,然后對其進行加工而super()就是將父類中的this對象繼承給子類的,沒有super()子類就得不到this對象
如果先調(diào)用this ,再初始化super(),同樣是禁止的行為
所以在子類的constructor 中 ,必須先用super 才能引用this
2. 類組件
在React中,類組件是基于es6的規(guī)范實現(xiàn)的,繼承React.Component,因此如果用到constructor就必須寫super()才初始化this
這時候,在調(diào)用super()的時候,我們一般都需要傳入props作為參數(shù),如果傳不進去,React內(nèi)部也會將其定義在組件實例中
// React 內(nèi)部 const instance = new YourComponent(props); instance.props = props;
所以無論有沒有constructor,在render中this.props都是可以使用的,這是React自動附帶的,是可以不寫的
class HelloMessage extends React.Component{
render(){
return <div>hello {this.props.name}</div>
}
}
但是也不建議使用super()代替super(props)因為在React會在類組件構(gòu)造函數(shù)生成實例后再給this.props附值,所以 不傳遞props在super的情況下,調(diào)用this.props為undefined,情況如下:
class Button extends React.Component{
constructor(props){
super() //沒傳入props
console.log(props) //{}
console.log(this.props) //undefined
}
}
而傳入props的則都能正常訪問,確保了this.props在構(gòu)造函數(shù)執(zhí)行完畢之前已經(jīng)被賦值,更符合邏輯
class Button extends React.Component{
constructor(props){
super(props) /
console.log(props) //{}
console.log(this.props) //{}
}
}
3. 總結(jié)
在React 中,類組件基于ES6,所以在constructor中必須使用super在調(diào)用super過程,無論是否傳入props,React內(nèi)部都會將props賦值給組件實例props屬性中,如果調(diào)用了super(),那么this.props在super和構(gòu)造函數(shù)結(jié)束之間仍然是undefined
到此這篇關(guān)于React中super()和super(props)的區(qū)別小結(jié)的文章就介紹到這了,更多相關(guān)React super()和super(props)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React-redux?中useSelector使用源碼分析
在一個 action 被分發(fā)(dispatch) 后,useSelector() 默認對 select 函數(shù)的返回值進行引用比較 ===,并且僅在返回值改變時觸發(fā)重渲染,,這篇文章主要介紹了React-redux?中useSelector使用,需要的朋友可以參考下2023-10-10
react component changing uncontrolled in
這篇文章主要為大家介紹了react component changing uncontrolled input報錯解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
可定制react18 input otp 一次性密碼輸入組件
這篇文章主要為大家介紹了可定制react18 input otp 一次性密碼輸入組件,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
聊一聊我對 React Context 的理解以及應(yīng)用
這篇文章主要介紹了聊一聊我對 React Context 的理解以及應(yīng)用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

