react中组件经常会重复使用,所以我们可以封装组件进行多功能的复用,常用的组件复用模式有:render props模式和高阶组件模式
高阶组件使用步骤:
- 创建一个以with开头函数(目前我们约定with开头的组件为高阶组件)
- 指定一个函数参数,首字母大写,作为渲染组件的组件名
- 函数内部创建一个类组件,用来提供用于复用的逻辑代码并返回
- 在高阶组件内渲染参数组件,将状态通过props传递给参数组件
- 调用高阶组件,传入想要增强的组件,通过返回值拿到新组建,并渲染到页面中
注意:react组件默认用组件名称为组件名,高阶组件渲染出的组件都是用高阶组件名作为组件名,多个渲染出来的组件名称是一样的,所以我们需要给高阶组件修改名称
import React from 'react'
function withMove(WrappedComponent) {
class App extends React.Component {
state = {
x: 0,
y:0
}
handleMouseMove=(e)=> {
this.setState({
x: e.clientX,
y: e.clientY,
})
}
componentDidMount() {
window.addEventListener('mousemove',this.handleMouseMove)
}
componentWillUnmount() {
window.removeEventListener('mousemove',this.handleMouseMove)
}
render() {
return (
<WrappedComponent {...this.state} />
)
}
}
App.displayName=`withMove${getDisplayName(WrappedComponent)}`
return App
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}
export default withMove
import withMove from './pages/comC'
const Position = props => (
<p>
鼠标位置:<br />
x:{props.x} <br />
y:{props.y}
</p>
)
const WithPosition = withMove(Position)
function App() {
return (
<WithPosition />
);
}