“为什么我的代码总是重复又重复?” —— 当我在第10次复制粘贴相同的权限检查逻辑时,终于崩溃了。直到发现高阶组件这个"代码复印机杀手",才明白React的组件复用可以如此优雅!本文将带你从零开始,逐步掌握高阶组件的各种骚操作,让你的代码从"复制粘贴地狱"升级到"优雅复用天堂"!
一、高阶组件基础:什么是HOC?
1.1 通俗理解高阶组件
高阶组件(Higher-Order Component)就像组件界的"套娃大师":
- 输入:一个普通组件
- 输出:一个增强版的新组件
- 原理:不修改原组件,而是通过包装来扩展功能
1.2 与普通组件的区别
特性 | 普通组件 | 高阶组件 |
---|---|---|
输入 | props | 组件 |
输出 | JSX | 新组件 |
作用 | 渲染UI | 增强功能 |
1.3 第一个HOC示例:给组件加边框
const withBorder = (WrappedComponent) => {
return (props) => (
<View style={
{borderWidth: 1, borderColor: 'red', padding: 10}}>
<WrappedComponent {...props} />
</View>
);
};
// 使用
const FancyButton = withBorder(Button);
二、HOC核心技巧:5种实用模式
2.1 属性代理模式
const withLogger = (WrappedComponent) => {
return (props) => {
console.log(`渲染组件: ${WrappedComponent.name}`);
return <WrappedComponent {...props} />;
};
};
适用场景:日志记录、属性校验、属性操作
2.2 状态抽象模式
const withLoading = (WrappedComponent) => {
return class extends React.Component {
state = { isLoading: true };
componentDidMount() {
setTimeout(() => this.setState({ isLoading: false }), 1000);
}
render() {
return this.state.isLoading ?
<ActivityIndicator /> :
<WrappedComponent {...this.props} />;
}
};
};
适用场景:加载状态、错误处理、数据获取
2.3 反向继承模式
const withAuth = (WrappedComponent) => {
return class extends WrappedComponent {
render() {
if (!this.props.isAuthenticated) {
return <LoginScreen />;
}
return super.render();
}
};
};
适用场景:条件渲染、覆盖生命周期
2.4 组合多个HOC
const EnhancedComponent = withRouter(