Executes a callback whenever an event occurs on the global object.
- Use the
useRef()
hook to create a variable,listener
, which will hold the listener reference. - Use the
useRef()
hook to create a variable that will hold the previous values of thetype
andoptions
arguments. - Use the
useEffect()
hook andEventTarget.addEventListener()
to listen to the given eventtype
on theWindow
global object. - Use
EventTarget.removeEventListener()
to remove any existing listeners and clean up when the component unmounts.
代码实现
const useOnGlobalEvent = (type, callback, options) => {
const listener = React.useRef(null);
const previousProps = React.useRef({ type, options });
React.useEffect(() => {
const { type: previousType, options: previousOptions } = previousProps;
if (listener.current) {
window.removeEventListener(
previousType,
listener.current,
previousOptions
);
}
listener.current = window.addEventListener(type, callback, options);
previousProps.current = { type, options };
return () => {
window.removeEventListener(type, listener.current, options);
};
}, [callback, type, options]);
};
使用样例
const App = () => {
useOnGlobalEvent('mousemove', e => {
console.log(`(${e.x}, ${e.y})`);
});
return <p>Move your mouse around</p>;
};
ReactDOM.createRoot(document.getElementById('root')).render(
<App />
);
翻译自:https://www.30secondsofcode.org/react/s/use-on-global-event