高阶组件:Higher-Order-Component
,简称 HOC,就是参数为组件,返回值为新组件的函数。高阶组件对原组件进行了一层拦截,就可以对原组件进行各种增强了。
高阶组件也有其缺点:HOC 需要对原组件进行包裹,如果大量使用 HOC,将会产生非常多的嵌套,会让调试变得困难;而且 HOC 可以劫持 pros,在不遵守约定的情况下可能会造成 props 的冲突。
高阶组件并不是 React API 的一部分,而是一种基于 React 的组合特性而形成的设计模式。
React.memo()
、React.forwardRef()
都是高阶函数。
// 定义高阶组件
function hoc(wrappedComponent) {
class enhancedComponent extends React.PureComponent {
render() {
// 高阶组件相当于对原组件进行了一层拦截,就可以对其进行增强了
return <wrappedComponent />
}
}
return enhancedComponent
}
// 使用高阶组件
const EnhancedComponent = hoc(WrappedComponent)
高阶组件的实现案例:通过高阶组件为自定义组件统一注入用户信息作为其 props。
// 定义高阶组件
function hoc(WrappedComponent) {
class EnhancedComponent extends React.PureComponent {
state = {
userInfo: {
name: 'Lee',
age: 18,
}
}
render() {
// 对原组件进行拦截,将 this.state.userInfo 作为 props 注入进行增强
return <WrappedComponent {...this.props} {...this.state.userInfo} />
}
}
return EnhancedComponent
}
// 定义原组件
function Profile(props) {
return <h1>Profile:{props.name} - {props.age}</h1>
}
// 使用高阶组件,生成增强后的组件
const EnhancedProfile = hoc(Profile)
// 使用增强后的组件
class App extends React.PureComponent {
render() {
return <EnhancedProfile/>
}
}