React获取鼠标在网页中移动时的位置

节流

const Mouse: React.FC = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 })
  useEffect(() => {
    //节流操作,优化频繁触发
    let timerId: null | NodeJS.Timeout = null
    const mouseMoveHandler = (e: MouseEvent) => {
      //频繁触发的return出去
      if (timerId != null) return
      timerId = setTimeout(() => {
        console.log({ x: e.clientX, y: e.clientY })
        setPosition({ x: e.clientX, y: e.clientY })
      //500后变为null
        timerId = null
      }, 500)
    }
    window.addEventListener('mousemove', mouseMoveHandler)
    return () => window.removeEventListener('mousemove', mouseMoveHandler)
  })
  return (
    <>
      

位置:{JSON.stringify(position)}

) } const TestMouseInfo: React.FC = () => { const [flag, setFlag] = useState(true) return ( <> {flag ? : null} ) } export default TestMouseInfo

你可能感兴趣的:(例子,javascript,前端,css)