react中实现鼠标跟随移动事件

import React, { Component } from 'react'

export default class Mouse extends Component {
  state = {
    x: 0,
    y: 0
  }

  componentDidMount() {
    window.addEventListener('mousemove', this.handleMouseMove)
  }

  componentWillUnmount() {
    window.removeEventListener('mousemove', this.handleMouseMove)
  }

  handleMouseMove = e => {
    this.setState({
      x: e.clientX,
      y: e.clientY
    })
  }

  render() {
    const { x, y } = this.state

    return (
      <div>
        {/* 推荐使用 children */}
        {this.props.children({ x, y })}
      </div>
    )
  }
}

上面的代码就已经完成了鼠标跟随移动的代码
在父组件进行引用Mouse组件时,直接使用Mouse组件children属性即可。

import React from 'react'

import Mouse from './Mouse'

import img from './images/cat.png'

const Cat = () => (
//这里就是使用了Mouse组件进行鼠标跟随
  <Mouse>
    {({ x, y }) => (
      <img
        src={img}
        alt=""
        style={{
          position: 'absolute',
          top: y - 64,
          left: x - 64
        }}
      />
    )}
  </Mouse>
)

export default Cat

你可能感兴趣的:(react,js)