useWinResize的使用

回到文章
<div id="app"></div>
<p>调节浏览器窗口试试看</p>
const { useState, useEffect, useCallback } = React;

const useWinResize = () => {
  const [size, setSize] = useState({
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight,
  });
  const resize = useCallback(() => {
    setSize({
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
    });
  }, []);
  useEffect(() => {
    window.addEventListener("resize", resize);
    return () => window.removeEventListener("resize", resize);
  }, []);
  return size;
};

const Home = () => {
  const { width, height } = useWinResize();

  return (
    <div>
      <p>width: {width}</p>
      <p>height: {height}</p>
    </div>
  );
};
ReactDOM.render(<Home />, document.getElementById("app"));