为什么高阶组件是组件?

问题描述 投票:1回答:1

我是React的新手,仍然在理解HOC上仍在努力。

我们知道:

HOC是一个接受组件并返回环绕它的新组件的函数。提供其他功能。

例如:

export function ProFeature(FeatureComponent) {
    return function(props) {
       if (props.pro) {
          let { pro, ...childProps} = props;
          return <FeatureComponent {...childProps} />
       } else {
         return (
            <h5 className="bg-warning text-white text-center">
                This is a Pro Feature
           </h5>
         )
      }
    }
}

因此ProFeature是HOC。

但是要将事物称为组件,它需要直接呈现内容。例如,对于名为customComponent的无状态组件,我们应该能够通过以下方式呈现其内容:

<customComponent />

但是我们不能在HOC上执行以下操作:

<ProFeature />   //invalid

相反,我们需要做:

let Abc = ProFeature(customComponent);

然后

<Abc/>

所以HOC不是组件吗?

reactjs high-order-component
1个回答
0
投票

“因此,HOC不是组件吗?”-不,为什么要这么做?正如React docs指出的那样:

“确切地说,高阶组件是一个接受组件并返回新组件的函数。”


let abc = ProFeature(customComponent);-它仍然无法正常工作,因为HOC是咖喱函数,您必须再次调用它以返回组件。

<abc />-由于组件名称必须大写,因此仍然无法使用:

const Abc = ProFeature(props)(customComponent);
<Abc />
© www.soinside.com 2019 - 2024. All rights reserved.