React類組件中super()和super(props)的區(qū)別詳解
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); this.age = age; } printAge(){ console.log(this.age); } } let tom = new sub("tom",20); tom.printName(); //tom tom.printAge(); //20
通過super關(guān)鍵字實現(xiàn)調(diào)用父類,super代替父類的構(gòu)建函數(shù),相當于調(diào)用sup.prototype.constructor.call(this,name),如果子類不適用super關(guān)鍵字會報錯,報錯的原因是子類沒有自己的this對象,他只是繼承父類的this對象,然后對其加工,也不能先用this,再調(diào)用super
類組件的繼承
類組件繼承React.Component,因此如果用到constructor就必須寫super(),才能初始化this,在調(diào)用super的時候一般要傳入props作為參數(shù),如果不傳進去,react內(nèi)部也會將其定義在組件實例中
// react內(nèi)部 const instance = new ExampleComponent(props); instance.props = props;
所以無論有沒有constructor,在render中的this.props都是可以使用的,在react中,使用super(),不傳入props,調(diào)用this.props為undefined,如下:
class Button extends React.Component{ constructor(props){ super(); console.log(this.props); //undefined } }
如果傳入props:
class Button extends React.Component{ constructor(props){ super(props); console.log(this.props); //{} } }
總結(jié)區(qū)別
不管是super()還是super(props),React內(nèi)部都會將props賦值給組件實例props屬性中,如果只調(diào)用super(),那么在構(gòu)造函數(shù)結(jié)束之前,使用this.props還是undefined
以上就是React類組件中super()和super(props)的區(qū)別詳解的詳細內(nèi)容,更多關(guān)于React super()和super(props)區(qū)別的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用react實現(xiàn)手機號的數(shù)據(jù)同步顯示功能的示例代碼
本篇文章主要介紹了使用react實現(xiàn)手機號的數(shù)據(jù)同步顯示功能的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04解讀react的onClick自動觸發(fā)等相關(guān)問題
這篇文章主要介紹了解讀react的onClick自動觸發(fā)等相關(guān)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02Reactjs?+?Nodejs?+?Mongodb?實現(xiàn)文件上傳功能實例詳解
今天是使用?Reactjs?+?Nodejs?+?Mongodb?實現(xiàn)文件上傳功能,前端我們使用?Reactjs?+?Axios?來搭建前端上傳文件應用,后端我們使用?Node.js?+?Express?+?Multer?+?Mongodb?來搭建后端上傳文件處理應用,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧2022-06-06