简体   繁体   中英

Is it possible to achieve something like HOC with classes - without classes in React?

I want to do something like:

<SomeProvider showConfirm={showConfirm}>
    {props.showConfirm()
    ? (<confirmActionComponent />)
    : (<chooseActionComponent />)}
</SomeProvider>

Inside of chooseActionComponent I want to be able to access showConfirm or another value in a deep nested child component to update some value in the parent and have confirmActionComponent show.

I know how to achieve this using class which tends to involve this and bind at some point, and I would prefer to avoid that.

Is there any way to accomplish something like this using pure functions/components instead? Would also prefer to keep this out of Redux store.

If you just want to access showConfirm , you simply can pass it to the child:

<SomeProvider showConfirm={showConfirm}>
    {props.showConfirm()
    ? (<confirmActionComponent />)
    : (<chooseActionComponent showConfirm={showConfirm} />)}
</SomeProvider>

Note following quote from React docs to inheritance:

At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies.


Anyway, I maybe have a really really dirty hack for you... use ref ...

const Child = () =>
    <div ref={(self) => {
        // get ReactDOMNode on stateless component
        const ReactDOMNode = self[Object.keys(self).filter((key) =>
            /__reactInternalInstance/g.test(key))[0]];

        // access parent props
        console.dir(ReactDOMNode
            ._hostParent
            ._currentElement
            ._owner
            ._currentElement
            .props);
    }}></div>;

Note: that this is not recommended and I won't recommend that, too. I would advice you to simply pass needed parent props to the child.

<SomeProvider showConfirm={showConfirm}>
    {props.showConfirm()
    ? (<confirmActionComponent />)
    : (<chooseActionComponent showConfirm={showConfirm} />)}
</SomeProvider>

And in your chooseActionComponent you can:

const chooseActionComponent = ({parentProps: {showConfirm}}) =>
    <div>{showConfirm}</div>;

You do not have to use ES6 classes to create React content. If you would like to avoid having to repeatedly use bind to ensure correct scoping of methods (that use this.setState / this.props ), you can revert back to using the React API helper functions ( see React without ES6 ).

You can specifically use: React.createClass for creating React classes and HOCs. Again, just to re-iterate this: using this alternative syntax will autobind this for you.

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