Higher-顺序组件
一句话解释
higher-顺序组件是 函数那个 takes 组件 and 返回新 enhanced 组件 — 模式 for sharing logic.
用大白话说
higher-顺序组件 (HOC) 是函数 Component => Component. It takes a component and returns a new one with added behavior. It's a pattern inspired by higher-order functions in functional programming.
const EnhancedComponent = withAuth(MyComponent) — withAuth is the HOC. It might check if the user is logged in and either render MyComponent or redirect to login.
HOCs were the primary way to share logic before Hooks. Today, custom Hooks are preferred because they are simpler, don't add nesting to the component tree, and are easier to type with TypeScript. HOCs are still seen in older codebases and some libraries (like React Redux's 连接).
示例
function withLoading(Component) {
return function WrappedComponent({ isLoading, ...props }) {
if (isLoading) return <Spinner />;
return <Component {...props} />;
};
}
const MyComponentWithLoading = withLoading(MyComponent);withLoading wraps 任何组件 and shows spinner 虽然 isLoading 是真, 否则渲染原始组件使用 remaining Props.
相关术语
相关资源
相关课程
- React 最佳实践
学习 HOCs and modern alternatives.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。