高阶组件(Higher-Order Component,HOC)是 React 中一种强大且灵活的模式,用于组件复用、逻辑抽象和增强组件功能。了解 HOC 的概念和使用方法对于掌握 React 开发是非常重要的。
// 一个简单的 HOC 示例
const withLog = (WrappedComponent) => {
return class WithLog extends React.Component {
componentDidMount() {
console.log("Component is mounted!");
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
// 使用 HOC 包装组件
const EnhancedComponent = withLog(MyComponent);
const withCounter = (WrappedComponent) => {
return class WithCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
render() {
return (
<WrappedComponent
count={this.state.count}
incrementCount={this.incrementCount}
{...this.props}
/>
);
}
};
};
const CounterComponent = ({ count, incrementCount }) => (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
const CounterWithHOC = withCounter(CounterComponent);
const withLocalStorage = (key) => (WrappedComponent) => {
return class WithLocalStorage extends React.Component {
componentDidMount() {
const data = localStorage.getItem(key);
if (data) {
this.setState({ data });
}
}
saveToLocalStorage = (data) => {
localStorage.setItem(key, data);
};
render() {
return (
<WrappedComponent
saveToLocalStorage={this.saveToLocalStorage}
{...this.props}
/>
);
}
};
};
const UserDataComponent = ({ saveToLocalStorage }) => (
<button onClick={() => saveToLocalStorage("user data")}>
Save to LocalStorage
</button>
);
const UserDataWithLocalStorage = withLocalStorage("userData")(UserDataComponent);
with
开头,以明确表达它是一个高阶组件。高阶组件是 React 中非常强大的工具,但使用时要注意不要过度使用,避免组件关系变得过于复杂。了解 HOC 的基本概念和用法后,还可以深入学习一些高级的 HOC 技巧,如传递静态方法、使用 forwardRef
等。
原文链接:codingdict.net