简体   繁体   中英

React: how to access base class from higher order components

So I have a BaseComponent.jsx that I extend on many of my components. This works great.

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
    }
}

But now I need to use withRouter(component) from react-router which wraps your component in a higher order component and decorates your class.

So I do this:

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

export default withRouter(OtherComponent)

The problem is that now I can't access the properties from BaseComponent and those return undefined .

How can I solve this so that I can create a HoC and at the same time access the properties of the base class?

Extending React components is discouraged by the React team. Even if it works on some instances, the results are unpredictable when doing fancier things such as higher order components.

General extending component classes should be avoided, and even if used, should not be used on "smart" connected components anyway – prefer composition over inheritance for React components.

And

You cannot implement a generic HoC that extends a component for the simple reason that the HoC has to work with all three forms of React component declaration.

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

So the answer to my question is simply that it can't be done and I should move to composition instead of inheritance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM