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></wrappedcomponent>
</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></enhancedmycomponent>;
}
export default App;
虽然 hoc 在引入 react hooks 之前更常用,但它们在很多情况下仍然有用。