繁体   English   中英

是否可以使用类实现类似HOC的东西-在React中不使用类?

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

我想做类似的事情:

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

chooseActionComponent内部,我希望能够访问showConfirm或深度嵌套的子组件中的另一个值,以更新父组件中的某些值并显示confirmActionComponent

我知道如何使用倾向于涉及到this并在某些时候bind class来实现这一点,我宁愿避免这种情况。

有没有办法使用纯函数/组件来完成类似的事情? 还希望将其保留在Redux商店之外。

如果只想访问showConfirm ,则可以将其传递给子级:

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

请注意以下从React文档引用到继承的引用:

在Facebook,我们在成千上万的组件中使用React,但还没有找到建议创建组件继承层次结构的用例。


无论如何,我可能会对您有一个非常肮脏的技巧...使用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>;

注意:不建议这样做,我也不建议这样做。 我建议您简单地将所需的父母道具传递给孩子。

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

在您的chooseActionComponent您可以:

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

您不必使用ES6类来创建React内容。 如果您希望避免重复使用bind来确保方法的正确作用域(使用this.setState / this.props ),则可以恢复使用React API帮助器函数请参阅不带ES6的React )。

您可以专门使用: React.createClass用于创建React类和HOC 再次,只是再次重申这一点:使用此替代语法会autobind this给你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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