react实现高阶组件
高阶组件(HOC)的基本概念
高阶组件是React中用于复用组件逻辑的一种高级技术,本质是一个函数,接收一个组件并返回一个新的组件。通过HOC可以将通用逻辑(如数据获取、权限控制)抽离,避免代码重复。
实现高阶组件的步骤
定义高阶组件函数
创建一个函数,接收原始组件作为参数,并返回一个新的增强组件。例如,一个用于添加日志功能的高阶组件:
function withLogging(WrappedComponent) {
return class extends React.Component {
componentDidMount() {
console.log(`Component ${WrappedComponent.name} mounted`);
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
使用高阶组件
通过调用高阶组件函数包装目标组件:
class MyComponent extends React.Component {
render() {
return <div>Hello, HOC!</div>;
}
}
const EnhancedComponent = withLogging(MyComponent);
高阶组件的常见用途
属性代理(Props Proxy)
通过高阶组件拦截或扩展传递给原始组件的props。例如,添加额外的属性:

function withExtraProps(WrappedComponent) {
return (props) => (
<WrappedComponent {...props} extraProp="additional data" />
);
}
反向继承(Inheritance Inversion)
通过继承原始组件控制其渲染行为。例如,条件渲染:
function withConditionalRendering(WrappedComponent) {
return class extends WrappedComponent {
render() {
if (this.props.isLoading) {
return <div>Loading...</div>;
}
return super.render();
}
};
}
注意事项
传递refs
使用React.forwardRef确保ref能正确传递到原始组件:

function withRefForwarding(WrappedComponent) {
return React.forwardRef((props, ref) => (
<WrappedComponent {...props} forwardedRef={ref} />
));
}
避免props命名冲突
确保高阶组件添加的props名称不与原始组件的props冲突,可通过命名空间或文档约定解决。
保持组件纯净
避免在高阶组件内部修改原始组件的原型或实例方法,遵循函数式编程的无副作用原则。
示例:数据请求高阶组件
以下是一个封装数据请求逻辑的高阶组件:
function withDataFetching(url) {
return function(WrappedComponent) {
return class extends React.Component {
state = { data: null, loading: true, error: null };
async componentDidMount() {
try {
const response = await fetch(url);
const data = await response.json();
this.setState({ data, loading: false });
} catch (error) {
this.setState({ error, loading: false });
}
}
render() {
return <WrappedComponent {...this.props} {...this.state} />;
}
};
};
}
// 使用
const UserListWithData = withDataFetching('https://api.example.com/users')(UserList);






