
react 中的高阶组件 (hoc) 是采用组件并返回具有增强功能的新组件的函数。它们允许您跨多个组件重用逻辑,而无需重复代码。
这是 hoc 的基本示例:
import React from 'react';
// A Higher-Order Component
function withExtraInfo(WrappedComponent) {
return function EnhancedComponent(props) {
return (
<div>
<p>This is extra info added by the HOC!</p>
<WrappedComponent {...props} />
</div>
);
};
}
// A regular component
function MyComponent() {
return <p>This is my component!</p>;
}
// Wrap the component with the HOC
const EnhancedMyComponent = withExtraInfo(MyComponent);
function App() {
return <EnhancedMyComponent />;
}
export default App;
hoc 的要点:
- 用途:用于向组件添加可重用逻辑(例如日志记录、权限等)。
- 纯函数:它们不会修改原始组件,而是返回一个新组件。
- 常见用例:授权、主题切换、数据获取等
虽然 hoc 在引入 react hooks 之前更常用,但它们在很多情况下仍然有用。










