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