1、创建高阶组件,代码如下:
import React from 'react'
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}
// 高阶组件
function WithHoc(WrappedComponent) {
class Hoc extends React.Component {
state = {
x: 0,
y: 0
}
moveMouse = e => {
this.setState({
x: e.clientX,
y: e.clientY
})
}
componentDidMount() {
window.addEventListener('mousemove', this.moveMouse)
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.moveMouse)
}
render() {
return <WrappedComponent {...this.state} {...this.props} />
}
}
Hoc.displayName = `WithHoc${getDisplayName(WrappedComponent)}`
return Hoc
}
export default WithHoc
2、组件运用
import React from 'react'
import WithHoc from './components/move-mouse/WithHoc'
function Mouse(props) {
return <p>鼠标当前坐标:{props.x},{props.y}</p>
}
const CoordMouse = WithHoc(Mouse)
function App() {
return (
<div className="App">
<CoordMouse />
</div>
)
}
export default App