2016-08-02 64 views
0

所以我有一個BaseComponent.jsx,我擴展了我的許多組件。這很好。反應:如何從高階組件訪問基類

class BaseComponent extends React.Component { 
    constructor(props){ 
     super(props) 
     this.something = true 
    } 
} 

class OtherComponent extends BaseComponent { 
    constructor(props){ 
     super(props) 
     console.log(this.something) // true 
    } 
} 

但現在我需要使用withRouter(component)react-router它包裝在一個高階組件的組件和裝飾類。

所以我這樣做:

class OtherComponent extends BaseComponent { 
    constructor(props){ 
     super(props) 
     console.log(this.something) // undefined 
    } 
} 

export default withRouter(OtherComponent) 

的問題是,現在我不能從BaseComponent訪問屬性和那些返回undefined

我該如何解決這個問題,以便創建一個HoC並同時訪問基類的屬性?

+0

我看不到相同的行爲。我根據你的例子創建了一個小提琴,它正確地記錄了'true'。補充一點,它應該像你所描述的一樣工作,並且由於HoC不會改變他們正在編寫的組件,因此這個小提琴就說明了這一點。 https://jsfiddle.net/okpLvu3e/ – ryanjduffy

+0

嘿@RyanDuffy這個簡單的例子可以工作,但是當你開始添加孩子等時,它不會。檢查這個:https://github.com/reactjs/react-router/issues/3514他們根本不建議擴展React.Component。 – Pier

+0

您可以使用組件組合來實現您想要的嗎?在開發React組件時,不鼓勵子類化。 – loganfsmyth

回答

-1

React團隊不鼓勵擴展React組件。即使它在某些情況下有效,但在做更高階組件等更有趣的事情時,結果也是不可預測的。

應該避免使用一般的擴展組件類,即使使用,也不應該在「智能」連接組件上使用 - 比React組件更喜歡組合繼承。

而且

無法實現擴展,原因很簡單,該組織已與所有三種形式作出反應組件聲明的工作組件的通用HOC。

來源:https://github.com/reactjs/react-router/issues/3514

所以回答我的問題很簡單,就是不能做,我應該搬到組成,而不是繼承。