简体   繁体   English

通过单击或点击外部关闭移动菜单

[英]Close the mobile menu by clicking or tapping outside


The code is for mobile menu but when I open it, it stays open and won't close. 该代码用于移动菜单,但是当我打开它时,它保持打开状态并且不会关闭。
I want it to close by clicking the menu links and tapping outside. 我希望通过单击菜单链接并在外部点击来关闭它。
I know I haven't even added in the code but I don't know how to add into it. 我知道我什至没有添加代码,但我不知道如何添加。
Can anyone help me with the code? 谁能帮我写代码? Any help is appreciated! 任何帮助表示赞赏!

Here is the code:这是代码:

 import { useState } from "react"; import { HiMenuAlt3, HiX } from "react-icons/hi"; export default function NavBar() { const [navbar, setNavbar] = useState(false); return ( <nav className="w-full bg-white shadow"> <div className="justify-between px-4 mx-auto lg:max-w-7xl md:items-center md:flex md:px-8"> <div> <div className="flex items-center justify-between py-3 md:py-5 md:block"> <a href="javascript:void(0)"> <h2 className="text-2xl font-bold">LOGO</h2> </a> <div className="md:hidden"> <button className="p-2 text-gray-700 rounded-md outline-none focus:border-gray-400 focus:border" onClick={() => setNavbar(?navbar)} > {navbar: ( <HiX className="text-4xl" /> // Close icon ): ( <HiMenuAlt3 className="text-4xl" /> // Open icon )} </button> </div> </div> </div> <div> <div className={`flex-1 justify-self-center pb-3 mt-8 md:block md:pb-0 md?mt-0 ${ navbar: "block": "hidden" }`} > <ul className="items-center justify-center space-y-8 md:flex md:space-x-6 md:space-y-0"> <li className="text-gray-600 hover:text-blue-600"> <a href="javascript:void(0)">Home</a> </li> <li className="text-gray-600 hover:text-blue-600"> <a href="javascript:void(0)">Blog</a> </li> <li className="text-gray-600 hover:text-blue-600"> <a href="javascript:void(0)">About US</a> </li> <li className="text-gray-600 hover:text-blue-600"> <a href="javascript;void(0)">Contact US</a> </li> </ul> </div> </div> </div> </nav> ); }

You do have code to close it, setNavbar(false) .您确实有关闭它的代码setNavbar(false) What you need is a hooked called useOnClickOutside .您需要的是一个名为useOnClickOutside的钩子。 https://usehooks.com/useOnClickOutside/ https://usehooks.com/useOnClickOutside/

To use it,要使用它,

function NavBar() {
  const ref = useRef()
  useOnClickOutside(ref, () => setNavbar(false));

  return (
    <nav ref={ref}>
      ...
    </nav>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM