
react 中的高阶组件 (hoc) 是采用组件并返回具有增强功能的新组件的函数。它们允许您跨多个组件重用逻辑,而无需重复代码。
这是 hoc 的基本示例:
import React from 'react';
// A Higher-Order Component
function withExtraInfo(WrappedComponent) {
return function EnhancedComponent(props) {
return (
This is extra info added by the HOC!
mallcloud商城
mallcloud商城基于SpringBoot2.x、SpringCloud和SpringCloudAlibaba并采用前后端分离vue的企业级微服务敏捷开发系统架构。并引入组件化的思想实现高内聚低耦合,项目代码简洁注释丰富上手容易,适合学习和企业中使用。真正实现了基于RBAC、jwt和oauth2的无状态统一权限认证的解决方案,面向互联网设计同时适合B端和C端用户,支持CI/CD多环境部署,并提
下载
);
};
}
// A regular component
function MyComponent() {
return This is my component!
;
}
// Wrap the component with the HOC
const EnhancedMyComponent = withExtraInfo(MyComponent);
function App() {
return ;
}
export default App;
hoc 的要点:
- 用途:用于向组件添加可重用逻辑(例如日志记录、权限等)。
- 纯函数:它们不会修改原始组件,而是返回一个新组件。
- 常见用例:授权、主题切换、数据获取等
虽然 hoc 在引入 react hooks 之前更常用,但它们在很多情况下仍然有用。









