[英]Close the mobile menu by clicking or tapping outside
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.