猿问

单击导航链接后无法关闭全屏菜单

问题


当我单击链接时,全屏菜单不想关闭。如果我使用 html 标签 a 并且一切正常,则 NavLink 元素会出现此问题。


这里我有一个功能,可以让我在按下其中一个链接时关闭。我之前提到过它仅适用于 href 标签。


import { useEffect } from "react";


export const useOnClickOutside = (ref, handler) => {

  useEffect(() => {

    const listener = (event) => {

      if (!ref.current || ref.current.contains(event.target)) {

        return;

      }

      handler(event);

    };

    document.addEventListener("mousedown", listener);

    return () => {

      document.removeEventListener("mousedown", listener);

    };

  }, [ref, handler]);

};

这是主菜单组件


const MobileMenu = () => {

  const [open, setOpen] = useState(false);

  const ref = useRef();


  useOnClickOutside(ref, () => setOpen(false));


  return (

    <MobileMenuWrapper ref={ref}>

      <BurgerIcon open={open} setOpen={setOpen} />

      <MobileMenuList open={open} setOpen={setOpen}>

        <MenuLinks />

      </MobileMenuList>

    </MobileMenuWrapper>

  );

};

和链接组件


const MenuLinks = () => {

  return (

    <>

      <ul>

        <li>

          <NavLink to="/"> Home</NavLink>

        </li>


        <li>

          <NavLink to="/albums">Albums</NavLink>

        </li>


        <li>

          <NavLink to="/addAlbum">Add Album</NavLink>

        </li>


        <li>

          <NavLink to="/about">About</NavLink>

        </li>


        <li>

          <NavLink to="/contact">Contact</NavLink>

        </li>

      </ul>

    </>

  );

};


慕神8447489
浏览 118回答 1
1回答

白板的微信

经过几个小时的搜索错误后我解决了它const [open, setOpen] = useState(false);&nbsp; const ref = useRef();&nbsp; // on link click change open to false&nbsp; useOutsideClick(ref, () => {&nbsp; &nbsp; if (open) setOpen(false);&nbsp; });&nbsp; return (&nbsp; &nbsp; <MobileMenuWrapper ref={ref}>&nbsp; &nbsp; &nbsp; <BurgerIcon open={open} setOpen={setOpen} />&nbsp; &nbsp; &nbsp; <MobileMenuList open={open} setOpen={setOpen}>&nbsp; &nbsp; &nbsp; &nbsp; <MenuLinks />&nbsp; &nbsp; &nbsp; </MobileMenuList>&nbsp; &nbsp; </MobileMenuWrapper>&nbsp; );和钩子export const useOutsideClick = (ref, callback) => {&nbsp; const handleClick = (e) => {&nbsp; &nbsp; if (ref.current && ref.current.contains(e.target)) {&nbsp; &nbsp; &nbsp; callback();&nbsp; &nbsp; }&nbsp; };&nbsp; useEffect(() => {&nbsp; &nbsp; document.addEventListener("click", handleClick);&nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; document.removeEventListener("click", handleClick);&nbsp; &nbsp; };&nbsp; });};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答