React中super()和super(props)的區(qū)別小結
1. ES6類
在ES6中,通過extends關鍵字實現(xiàn)類的繼承,方式如下:
class sup{ constructor(name){ this.name=name; } printName(){ console.log(this.name) } } class sub extends sup{ constructor(name,age){ super(name) //super 代表的是父類的構造函數(shù) this.age=age; } printAge(){ console.log(this.age) } } let rui=new sub('rui',21); rui.printAge() //21 rui.printName() //rui
在上面的例子在子中,可以看到通過super關鍵字實現(xiàn)調用父類,super代替的是父類的構建函數(shù),使用super(name)相當于調sup.prototype.constructor.call(this.name)
如果在子類中不使用super關鍵字,則會引發(fā)報錯
報錯的原因是 子類沒有自己的this對象,它只能繼承父類的this對象,然后對其進行加工而super()就是將父類中的this對象繼承給子類的,沒有super()子類就得不到this對象
如果先調用this ,再初始化super(),同樣是禁止的行為
所以在子類的constructor 中 ,必須先用super 才能引用this
2. 類組件
在React中,類組件是基于es6的規(guī)范實現(xiàn)的,繼承React.Component,因此如果用到constructor就必須寫super()才初始化this
這時候,在調用super()的時候,我們一般都需要傳入props作為參數(shù),如果傳不進去,React內部也會將其定義在組件實例中
// React 內部 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會在類組件構造函數(shù)生成實例后再給this.props附值,所以 不傳遞props在super的情況下,調用this.props為undefined,情況如下:
class Button extends React.Component{ constructor(props){ super() //沒傳入props console.log(props) //{} console.log(this.props) //undefined } }
而傳入props的則都能正常訪問,確保了this.props在構造函數(shù)執(zhí)行完畢之前已經被賦值,更符合邏輯
class Button extends React.Component{ constructor(props){ super(props) / console.log(props) //{} console.log(this.props) //{} } }
3. 總結
在React 中,類組件基于ES6,所以在constructor中必須使用super在調用super過程,無論是否傳入props,React內部都會將props賦值給組件實例props屬性中,如果調用了super(),那么this.props在super和構造函數(shù)結束之間仍然是undefined
到此這篇關于React中super()和super(props)的區(qū)別小結的文章就介紹到這了,更多相關React super()和super(props)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
react-router browserHistory刷新頁面404問題解決方法
本篇文章主要介紹了react-router browserHistory刷新頁面404問題解決方法,非常具有實用價值,需要的朋友可以參考下2017-12-12React實現(xiàn)歌詞滾動效果(跟隨音樂播放時間滾動)
這篇文章主要為大家詳細介紹了React實現(xiàn)歌詞滾動效果(跟隨音樂播放使勁按滾動),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2024-02-02React關于antd table中select的設值更新問題
這篇文章主要介紹了React關于antd table中select的設值更新問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03使用 Rails API 構建一個 React 應用程序的詳細步驟
這篇文章主要介紹了使用 Rails API 構建一個 React 應用程序的詳細步驟,主要包括后端:Rails API部分,前端:React部分及React組件的相關操作,具有內容詳情跟隨小編一起看看吧2021-08-08react18中react-redux狀態(tài)管理的實現(xiàn)
本文主要介紹了react18中react-redux狀態(tài)管理的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05解析react?函數(shù)組件輸入卡頓問題?usecallback?react.memo
useMemo是一個react hook,我們可以使用它在組件中包裝函數(shù)??梢允褂盟鼇泶_保該函數(shù)中的值僅在依賴項之一發(fā)生變化時才重新計算,這篇文章主要介紹了react?函數(shù)組件輸入卡頓問題?usecallback?react.memo,需要的朋友可以參考下2022-07-07