Open
Description
用于对一个元素进行监听:鼠标是否在停留在该元素上,并提供回调函数,可以在鼠标放到元素上触发动作,比如触发动画回调,还有更复杂一些的场景弹出一个浮框内容,浮框跟着鼠标在该元素运动
API
function useMouseInElement(target?: BasicTarget, inCallback?: (result: Result) => void, outCallback?: (result: Result) => void)
Demo
import { useMouseInElement } from 'ahooks';
import React, { useRef } from 'react';
const App: React.FC = () => {
const ref = useRef<HTMLDivElement>(null);
const { isInside } = useMouseInElement(
ref.current,
() => {
console.log('inside');
},
() => {
console.log('outside');
},
);
return (
<div>
<div
ref={ref}
style={{ width: 200, height: 200, padding: 12, border: '1px solid #000', marginBottom: 8 }}
>
isInside:{String(isInside)}
</div>
</div>
);
};
export default App;