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並同時訪問基類的屬性?
我看不到相同的行爲。我根據你的例子創建了一個小提琴,它正確地記錄了'true'。補充一點,它應該像你所描述的一樣工作,並且由於HoC不會改變他們正在編寫的組件,因此這個小提琴就說明了這一點。 https://jsfiddle.net/okpLvu3e/ – ryanjduffy
嘿@RyanDuffy這個簡單的例子可以工作,但是當你開始添加孩子等時,它不會。檢查這個:https://github.com/reactjs/react-router/issues/3514他們根本不建議擴展React.Component。 – Pier
您可以使用組件組合來實現您想要的嗎?在開發React組件時,不鼓勵子類化。 – loganfsmyth