HOC:高阶组件 高阶组件就是一个函数,接收一个组件作为参数,返回一个新的组件。
- 示例:鼠标移动,获取鼠标位置 x、y 的值。
1.封装一个高阶组件:
// WrappedComponent 是一个组件,作为参数传入
const withMouse = (WrappedComponent) => {
// 重新定义一个类组件
class withMouseComponent extends React.Component {
constructor(props) {
super(props)
// x、y 初始值设置为 0
this.state = { x: 0, y: 0 }
}
handleMouseMove = (event) => {
// 鼠标移动,重新赋值 x、y
this.setState({
x: event.clientX,
y: event.clientY
})
}
render() {
return (
<div style={{ height: '500px' }} onMouseMove={this.handleMouseMove}>
{/* 1. 透传所有 props 2. 增加 mouse 属性 */}
<WrappedComponent {...this.props} mouse={this.state}/>
</div>
)
}
}
// 返回新的组件
return withMouseComponent
}
2.使用组件
// 创建一个函数组件App
const App = (props) => {
// 由于上面封装的组件透传了 props,可以在这里获取组件上的属性
const testProp = props.testProp
const { x, y } = props.mouse // 接收 mouse 属性
return (
{/* 写一个简单的容器,显示鼠标的位置 */}
<div style={{ height: '500px' }}>
<h1>The mouse position is ({x}, {y})</h1>
<p>{ testProp }</p>
</div>
)
}
// App作为高阶组件的参数传入 withMouse
const HOCDemo = withMouse(App);
// render 里面使用组件
<HOCDemo testProp="测试透传属性" />