30秒学会 React 片段 · 2022年12月8日

30秒学会 React 片段 – React useOnWindowScroll hook

Executes a callback whenever the window is scrolled.

  • Use the useRef() hook to create a variable, listener, which will hold the listener reference.
  • Use the useEffect() hook and EventTarget.addEventListener() to listen to the 'scroll' event of the Window global object.
  • Use EventTarget.removeEventListener() to remove any existing listeners and clean up when the component unmounts.

代码实现

const useOnWindowScroll = callback => {
  const listener = React.useRef(null);

  React.useEffect(() => {
    if (listener.current)
      window.removeEventListener('scroll', listener.current);
    listener.current = window.addEventListener('scroll', callback);
    return () => {
      window.removeEventListener('scroll', listener.current);
    };
  }, [callback]);
};

使用样例

const App = () => {
  useOnWindowScroll(() => console.log(`scroll Y: ${window.pageYOffset}`));
  return <p style={{ height: '300vh' }}>Scroll and check the console</p>;
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <App />
);

翻译自:https://www.30secondsofcode.org/react/s/use-on-window-scroll