当前位置: 首页 > news >正文

何为高阶组件(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)是一个以组件为输入,返回新组件的函数,
主要用于逻辑复用与功能增强。

http://icebutterfly214.com/news/176/

相关文章:

  • 销售公司绩效考核全攻略:维度、原则与数字化赋能方案
  • 题解:P4434 [COCI 2017/2018 #2] ​​Usmjeri
  • 小程序-跳转到公众号
  • 如何解决一堆向量的问题?10、Self-attention - -一叶知秋
  • 洞悉过往,一目了然:浅述视频融合平台EasyCVR如何实现海量视频录像的智能检索与高效回看
  • 2025年国内外五款AI编程工具深入对比与推荐排行
  • CSPS 前后的话
  • 2025 年 10 月云仓 ERP,云仓 saas 系统,云仓代发系统公司最新推荐,技术实力与市场口碑深度解析
  • iOS混淆实战用多工具组合把IPA加固做成可复用的工程能力(iOS混淆 IPA加固 无源码混淆
  • cyclonessd ROS2 lidar topic 数据丢帧 系统配置
  • 2025 年 10 月 WMS 系统,WMS 软件,wms 仓储管理系统公司最新推荐,聚焦资质、案例、售后的优质机构深度解读
  • Go语言测试全攻略:从单元测试到模糊测试
  • 2025 年 10 月进销存 erp,供应链 erp,零售 ERP 公司最新推荐,聚焦资质、案例、售后的五家机构深度解读!