useMousePosition
useMousePosition 功能为记录鼠标移动的x 轴
和y 轴
语法
定义 hook
import React, {useState, useEffect} from 'react';
type PositionType = {
x: number;
y: number;
};
const useMousePosition = () => {
const [positions, setPositions] = useState<PositionType>({x: 0, y: 0});
const updateMouse = (e: MouseEvent) => {
setPositions(() => ({x: e.clientX, y: e.clientY}));
};
useEffect(() => {
document.addEventListener('mousemove', updateMouse);
return () => {
document.removeEventListener('mouseleave', updateMouse);
};
}, []);
return positions;
};
export default useMousePosition;
使用 hook
import React from 'react';
import useMousePosition from './hooks/useMousePosition';
function App() {
const positions = useMousePosition();
return (
<div>
<div>
x: {positions.x}, y: {positions.y}
</div>
</div>
);
}
export default App;