何为高阶组件(higherordercomponent) ?

定义

高阶组件(Higher-Order Component,简称 HOC)
是一个 接受组件作为参数,并返回一个新组件的函数。

简单来说:

HOC = 组件的“加工厂”
它给组件“增强功能”,返回一个功能更强的组件。

核心公式

const EnhancedComponent = higherOrderComponent(WrappedComponent);
  • WrappedComponent:被包裹的原始组件

  • higherOrderComponent:高阶组件函数

  • EnhancedComponent:增强后的新组件

通俗类比

假设你有一个普通人 人类A,
然后有一个函数叫 withSuperPower(人),它会给人加上“飞行”能力。

const 超人 = withSuperPower(人类A);

这个 withSuperPower 就是高阶函数。
在 React 中,这个理念应用在组件上,就是 高阶组件。

代码示例

打印日志的高阶组件
function withLogger(WrappedComponent) {
  return function EnhancedComponent(props) {
    console.log('Props:', props);
    return <WrappedComponent {...props} />;
  };
}

使用:

function Hello(props) {
  return <h1>Hello, {props.name}</h1>;
}

const HelloWithLogger = withLogger(Hello);

渲染时:

<HelloWithLogger name="Alice" />

输出:

Props: { name: 'Alice' }
Hello, Alice
鉴权(Auth)高阶组件
function withAuth(WrappedComponent) {
  return function AuthenticatedComponent(props) {
    const isLogin = localStorage.getItem('token');
    if (!isLogin) {
      return <div>请先登录</div>;
    }
    return <WrappedComponent {...props} />;
  };
}

使用:

const ProfilePage = withAuth(UserProfile);

特点总结

特点 说明
输入 一个组件
输出 一个新组件
作用 逻辑复用、增强组件功能
常见应用 权限控制、日志打印、埋点统计、数据注入等
对比 Hooks HOC 是类组件时代常用的逻辑复用手段,函数组件中更多用自定义 Hooks 代替

注意事项

  • 不要在 render 里使用 HOC(会导致组件频繁重新创建)

  • 拷贝静态方法时需要手动处理(例如使用 hoist-non-react-statics)

  • 命名规范:通常以 with 开头(例如:withRouter, withAuth)

一句话总结:

高阶组件(HOC)是一个以组件为输入,返回新组件的函数,
主要用于逻辑复用与功能增强。

posted @ 2025-10-27 16:11  煜火  阅读(1)  评论(0)    收藏  举报