2017-09-29 126 views
0

有人能解釋爲什麼你必須提供props關鍵字給構造函數嗎?我認爲當你構建組件時,樹從上往下工作......這意味着道具最終將用於子組件。道具參數/參數如何在構造關鍵字中使用React?

我記得在播客中聽到凱爾辛普森是一位嘉賓,他說「超級」關鍵詞是在基於類的系統中獲得相對多態引用(從方法到基類)的一種方式。或者根據我的理解,這就是語法糖的工作原理,因爲在封面下它是一個委託模式。

預先感謝您!

import React, {Component} from 'react' 

class App extends Component { 

    constructor(props) { 
    super(props) 
    this.state = { 
     warpDriveCapacity : 10 
    } 
    } 

} 

回答

1

如果要在構造函數中使用「this.props」,則需要將props傳遞給super。否則,這並不重要,因爲React在調用構造函數後立即在外部設置.props實例。

例如:

export class ComponentName extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     stateKey: props.initialProps 
    }; 
    } 
    //... 
} 
相關問題