高阶组件 HOC higher order component
概述
- 目的:实现状态逻辑复用 增强一个组件的能力
- 采用 包装(装饰)模式,高阶组件通过包装组件,增强组件功能
思路分析
- 高阶组件(HOC,Higher-Order Component)是一个函数,接收要包装的组件,返回增强后的组件
- 高阶组件的命名:
withMouse withRouter withXXX
- 高阶组件内部创建一个类组件,在这个类组件中提供复用的状态逻辑代码,通过prop将复用的状态传递给 被包装组件
const CatWithMouse = withMouse(Cat)
const PositionWithMOuse = withMouse(Position)
const WithMouse = (Base) => {
class Mouse extends React.Component {
render() {
return <Base {...this.state} />
}
}
return Mouse
}
使用步骤
- 创建一个函数,名称约定以 with 开头
- 指定函数参数(作为要增强的组件) 传入的组件只能渲染基本的UI
- 在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回
- 在内部创建的组件的render中,需要渲染传入的基本组件,增强功能,通过props的方式给基本组件传值
- 调用该高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,并将其渲染到页面中
const MousePosition = withMouse(Position)
<MousePosition />
传递props
- 问题:props丢失
- 原因:高阶组件没有往下传递props
- 解决方式:渲染 WrappedComponent 时,将 state 和 this.props 一起传递给组件
- 传递方式:
<WrappedComponent {...this.state} {...this.props} />