使用反应挂钩的响应侧边栏

Responsive sidebar using react hooks

我正在尝试调试我的侧边栏遇到的问题,但无法弄清楚我做错了什么。侧边栏根据 innerWidth 正确折叠,但是当我在第一次加载移动视图时,侧边栏展开而不是像假设的那样折叠。 任何向我解释错误的帮助都会很棒。 非常感谢 这是我的片段:

export default function Sidebar() {
  const location = useLocation();
  let { pathname } = location;

  const [isNavOpen, setIsNavOpen] = useState(true);

  useEffect(() => {
    window.addEventListener("resize", () => {
      if (window.innerWidth <= 767) {
        setIsNavOpen(false);
      }
      else if (window.innerWidth >= 767) {
        setIsNavOpen(true);
      }
    });
  });

  return (
    <div className="menu-bar">
      <Menu
        width={210}
        isOpen={isNavOpen}
        noOverlay
        pageWrapId={"page-wrap"}
        outerContainerId={"outer-container"}
        disableAutoFocus
        disableCloseOnEsc
      >

您的初始状态是 true,因此当应用程序启动时,边栏是打开的。只要您不调整大小,就不会调用事件处理程序。

将定义isNavOpen状态的逻辑提取到一个函数中,并调用它来创建初始值,然后在调整window大小时:

const { useState, useEffect } = React;

const shouldBeOpen = () => window.innerWidth > 767

function Sidebar() {
  const [isNavOpen, setIsNavOpen] = useState(shouldBeOpen);

  useEffect(() => {
    window.addEventListener("resize", () => {
      setIsNavOpen(shouldBeOpen());
    });
  }, []);

  return isNavOpen ? 'open' : 'close'
}

ReactDOM.render(
  <Sidebar />,
  root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

此外,在这种情况下我更喜欢使用window.matchMedia(), which is the JS equivalent to CSS media queries. I've created a useMatchMedia hook which you can see in this