高阶组件 vs 封装组件

高阶组件(HOC) vs 包裹组件(Wrapped Component)

先给用例

function HOC(Component) {
  return class extends React.Component {
    name: string = "";
    render() {
      return (
        <>
          <Component addtionalProp={name} />
          <button type="button">Click Me</button>
        </>
      );
    }
  };
}

function WrapperComponent(props) {
  let name: string = "";
  return (
    <>
      {React.cloneElement(props.children, { addtionalProps: name })}
      <button type="button">Click Me</button>
    </>
  );
}

结论
相同点:

  • 它们都是给组件添加一些额外的功能

不同点:

  • HOC 添加的功能对于 Component 而言是可知的,或者说,HOC 提供的信息是 Component 定义里面的某个属性,只是,Component 不关心它的来源,是来自 HOC 还是来自于业务代码都无所谓。封装组建(Wrapped Component),添加的内容一般组件是完全不知道的。
  • HOC 添加的功能是在 Component 构建之前,而 WrappedComponent,则是在组件构建之后,通过 React.cloneElement 重新创建。效率更低。
posted @ 2021-12-27 20:37  kongshu  阅读(94)  评论(0编辑  收藏  举报