在 React 中获取鼠标位置(坐标)

在 React 中获取鼠标位置:

  1. 在元素上设置 onMouseMove 属性或在窗口对象上添加事件侦听器。
  2. 提供事件处理函数。
  3. 访问事件对象的相关属性。
import {useEffect, useState} from 'react';

export default function App() {
  const [coords, setCoords] = useState({x: 0, y: 0});

  const [globalCoords, setGlobalCoords] = useState({x: 0, y: 0});

  useEffect(() => {
    // ?️ get global mouse coordinates
    const handleWindowMouseMove = event => {
      setGlobalCoords({
        x: event.screenX,
        y: event.screenY,
      });
    };
    window.addEventListener('mousemove', handleWindowMouseMove);

    return () => {
      window.removeEventListener('mousemove', handleWindowMouseMove);
    };
  }, []);

  const handleMouseMove = event => {
    setCoords({
      x: event.clientX - event.target.offsetLeft,
      y: event.clientY - event.target.offsetTop,
    });
  };

  return (
    <div>
      {/* ?️ Get mouse coordinates relative to element */}
      <div
        onMouseMove={handleMouseMove}
        style={{padding: '3rem', backgroundColor: 'lightgray'}}
      >
        <h2>
          Coords: {coords.x} {coords.y}
        </h2>
      </div>

      <hr />

      <h2>
        Global coords: {globalCoords.x} {globalCoords.y}
      </h2>
    </div>
  );
}

在 React 中获取鼠标位置(坐标)

代码示例显示了如何处理 div 元素或 window 对象上的 mousemove 事件。

mousemove 事件在光标热点位于元素内部时移动用户鼠标时在元素处触发。

要获得相对于页面上元素的鼠标坐标,我们必须从 clientX 中减去 offsetLeft,从 clientY 中减去 offsetTop。

// ?️ get mouse coords relative to the an element
const handleMouseMove = event => {
  setCoords({
    x: event.clientX - event.target.offsetLeft,
    y: event.clientY - event.target.offsetTop,
  });
};

offsetLeft 属性返回当前元素的左上角在 offsetParent 节点内向左偏移的像素数。

offsetTop 属性返回当前元素的外边框相对于位置最近的祖先元素的内边框之间的像素数。

clientX 属性返回事件发生时应用程序视口内的水平坐标。

clientY 属性返回事件发生时应用程序视口内的垂直坐标。

第二个示例显示如何监听窗口对象上的 mousemove 事件以获取全局鼠标坐标。

useEffect(() => {
  // ?️ get global mouse coordinates
  const handleWindowMouseMove = event => {
    setGlobalCoords({
      x: event.screenX,
      y: event.screenY,
    });
  };
  window.addEventListener('mousemove', handleWindowMouseMove);

  return () => {
    window.removeEventListener('mousemove', handleWindowMouseMove);
  };
}, []);

我们将一个空的依赖数组传递给 useEffect 钩子,因为我们只想注册一次粘贴事件侦听器 – 当组件挂载时。

我们从 useEffect 钩子返回的函数在组件卸载时被调用。

我们使用 removeEventListener 方法来移除我们之前注册的事件监听器。

清理步骤很重要,因为我们要确保我们的应用程序中没有任何内存泄漏。

screenX 属性返回鼠标在全局屏幕坐标中的水平坐标(偏移量)。

screenY 属性返回鼠标在全局坐标中的垂直坐标(偏移量)。