在React中定义和导出HOC [英] Defining and exporting HOC in React

查看:84
本文介绍了在React中定义和导出HOC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究高阶组件的反应。我的要求是我有一组需要扩展的组件,以便在不重写整个组件的情况下提供更多功能。在这种情况下,我发现了反应中的HOC概念,即可以使用纯函数扩展组件。我的问题是,我可以将扩展组件导出为普通组件吗?例如

I've been research Higher Order Components in react. My requirement is that I have a set components which I need to extend to give them more functionality without rewriting the entire component. In this case, I found out the concept HOC in react where one could extend the component using a pure function. My question is, can I export the extended component as a normal component. For an example

需要扩展的组件

class foo extends React.Component {
    render(){
        //something
    }
}

export default foo;

HOC组件

function bar(foo) {
    render() {
         return <foo {...this.props} {...this.state} />;
    }
}

export default bar;

我可以使用该组件吗?还是我做错了?

Am I able to use the component that way? or am I doing it wrong?

推荐答案

HOC将获取一个组件,添加更多功能并返回一个新组件,而不仅仅是返回该组件实例,

A HOC would take a component, add some more functionality and return a new component and not just return the component instance,

您将要做的

function bar(Foo) {

   return class NewComponent extend React.Component {
        //some added functionalities here
        render() {
            return <Foo {...this.props} {...otherAttributes} />
        }
   }

}

export default bar;

现在,当您想向组件中添加某些功能时,您将创建组件实例,例如

Now when you want to add some functionality to a component you would create a instance of the component like

const NewFoo = bar(Foo);

现在您可以像这样使用

return (
    <NewFoo {...somePropsHere} />
)

此外,您可以允许HOC接受默认组件并将其导出为默认组件,并在其他地方使用它,例如

Additionally you could allow the HOC to take a default component and export that as a default component and use it elsewhere like

function bar(Foo = MyComponent) {

然后创建一个导出例如

const wrapMyComponent = Foo();
export { wrapMyComponent as MyComponent };

HOC的典型用例可以是 HandleClickOutside 功能,通过该功能,您可以传递需要根据 handleClickOutside 功能

A typical use-case of an HOC could be a HandleClickOutside functionality whereby you would pass a component that needs to take an action based on handleClickOutside functionality

这篇关于在React中定义和导出HOC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆