Executes a callback whenever the window is resized.
- Use the
useRef()
hook to create a variable,listener
, which will hold the listener reference. - Use the
useEffect()
hook andEventTarget.addEventListener()
to listen to the'resize'
event of theWindow
global object. - Use
EventTarget.removeEventListener()
to remove any existing listeners and clean up when the component unmounts.
代码实现
const useOnWindowResize = callback => {
const listener = React.useRef(null);
React.useEffect(() => {
if (listener.current)
window.removeEventListener('resize', listener.current);
listener.current = window.addEventListener('resize', callback);
return () => {
window.removeEventListener('resize', listener.current);
};
}, [callback]);
};
使用样例
const App = () => {
useOnWindowResize(() =>
console.log(`window size: (${window.innerWidth}, ${window.innerHeight})`)
);
return <p>Resize the window and check the console</p>;
};
ReactDOM.createRoot(document.getElementById('root')).render(
<App />
);
翻译自:https://www.30secondsofcode.org/react/s/use-on-window-resize