class實現React繼承以及constructor的super的問題

看這篇文章以前 建議先看看 阮一峯 的Class繼承 便於更好的理解
首先要知道一個問題
React的父子組件和組件類的繼承有什麼關係?答案是:沒有關係
父子組件:指的得是組件標籤包含關係 父子組件經過這種關係實現組件通訊
組件繼承:經過class實現繼承關係
 
es6中class實現的繼承
class Father { constructor() { this.name = 'zhangsan' } getDate = (data) => { this.haha() //由於繼承關係 因此這個this也指向子組件實例 因此可調用子組件的方法
 } getName() { console.log('父組件的name') } } class Son extends Father {//extends至關於繼承了父組件的全部屬性和方法
 constructor(props) { super(props) console.log("this", this) } haha = () => { console.log('子組件的哈哈') } getName = () => { super.getName();//若是不但願本身的getName覆蓋父親組件的getName
        console.log('子組件的name') } } let son = new Son(); console.log('son 實例', son) son.getDate() //子組件的哈哈
    son.getName() //父組件的name 子組件的name

看到上面的代碼會發現:react

 說明Es6裏 類裏面的this 指向實例對象new Son()es6

 

那麼問題來啦,請問react組件Son裏面的this也是徹底等價於實例對象new Son()嗎? 答案是否:react組件裏this=new Son()實例+React包裝 函數

Button父組件:用來給子組件傳遞props this

import React from 'react';
import Son from './son';
function Button() {
return <div>
<Son name='sun sun sun' /> {/*子組件 等價於new Son()+react包裹 */}
</div>
}
export default Button;

Father父組件spa

import React from 'react'; class Father extends React.Component { constructor(props) { super(props) this.moduleName = 'moduleName'; } getDate = () => { this.haha() } getName() { //不能用作箭頭函數 若是是箭頭函數則會報錯 由於自組件的方法中super.getName()中的super指向的是Father類 若是是箭頭函數 指向的是Son的實例對象
    console.log('父組件的name') } render() { return 'father' } } export default Father

Son子組件3d

 
class Son extends Father{
constructor(props) { super(props); console.log("this", this) } haha = () => { console.log('子組件的哈哈') } getName = () => { super.getName(); console.log('子組件的name') } render() { return <div>
      <button onClick={this.getName}>點擊獲取name</button>
      <button onClick={this.getDate}>點擊獲取父親組件的getDate方法</button>
    </div>
 } } let son = new Son('我是Son的實例參數') //子組件的哈哈
console.log('Son的實例', son) //父組件的name 子組件的name
son.getName() son.getDate() export default Son

 

因此說:react中的this 等價於 new Son()+React內部方法的集合  
code

 

 那麼問題來啦,組件的constructor方法必需要寫嗎? super必需要加嗎?super裏面的參數必需要寫嗎?對象

 1.組件的constructor方法必需要寫嗎blog

若是子類沒有定義constructor方法,這個方法會被默認添加,代碼以下。也就是說,無論有沒有顯式定義,任何一個子類都有constructor方法。繼承

class ColorPoint extends Point { } // 等同於 
class ColorPoint extends Point { constructor(...args) { super(...args); } } // 可見沒有寫constructor,在執行過程當中會自動補上

2.若是constructor()方法定義啦 isuper必需要加嗎? 答案是:必需要加

3.super()裏面的參數必需要寫嗎? 答案是:可寫可不寫 若是想要在constructor()裏面使用this.props 則須要傳遞參數

 

若是子類super() 不傳遞props/或者傳遞props constructor(props) { super(); console.log("子類this.props", this.props) } 父親類別 constructor() { super() console.log("父類this.props", this.props) }

 

若是子類super()傳遞props constructor(props) { super(props); console.log("子類this.props", this.props) } 父類super()傳遞props constructor(props) { super(props) console.log("父類this.props", this.props) }

總結:由於父組件也是繼承於 React.Component 因此要想在當前組件裏在constructor()裏使用this.props 則須要給他的每一層的父組件的super裏面加props才能生效值

相關文章
相關標籤/搜索