1、创建PropsRender组件,代码如下:
import React from 'react'
export default class PropsRender 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 this.props.render(this.state)
}
}
2、组件运用
import React from 'react'
import PropsRender from './components/move-mouse/PropsRender'
function App() {
return (
<div className="App">
<PropsRender render={
move => {
return (<p>鼠标当前坐标:{move.x},{move.y}</p>)
}
}></PropsRender>
)
}
export default App