使用 Hooks 折叠 React 边栏

Collapse React Sidebar using Hooks

我需要根据屏幕尺寸折叠边栏。到目前为止,我的所有尝试都不走运。我想知道是否有人可以通过使用 Hooks 给我一些提示。 状态设置为“isOpen={true}”,当宽度达到 768px 或更低时,我需要将其设置为 false。

提前致谢

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

这是一个缩小的例子:


import React, { useState, useEffect } from "react";

export default function App() {
  const [isNavOpen, setIsNavOpen] = useState(true);

  useEffect(() => {
    window.addEventListener("resize", () => {
      if (window.innerWidth <= 768) {
        setIsNavOpen(false)
      }
    })
    return window.removeEventListener("resize", () => {
      if (window.innerWidth <= 768) {
        setIsNavOpen(false)
      }
    })
  })

  return (
    <div className="nav">
      <Nav isOpen{isNavOpen}/>
    </div>
  );
}


此自定义挂钩根据传递的查询使用 Window.matchMedia() 到 return 布尔值:

const { useMemo, useState, useEffect } = React

const useMediaQuery = query => {
  const mql = useMemo(() => window.matchMedia(query))

  const [match, setMatch] = useState(mql.matches)

  useEffect(() => {
    const handler = e => setMatch(e.matches)
    mql.addListener(handler)
    
    return () => {
      mql.removeListener(handler)
    }
  }, [mql])
  
  return match
}

const Demo = () => {
  const close = useMediaQuery('(max-width: 600px)')
  
  return (
    <div className="container">
      {close || <aside />}
      <main />
    </div>
  )
}

ReactDOM.render(
  <Demo />,
  root
)
.container {
  display: flex;
  height: 75vh;
}

main {
  flex: 4;
  height: 100%;
  background: purple;
}

aside {
  flex: 1;
  height: 100%;
  background: gold;
}
<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>