Shadcn UI Sheet组件跳转后无法自动关闭的解决方法
解决Next.js + shadcn/ui Sheet移动端菜单跳转后不关闭的问题
方案一:受控Sheet模式,监听路由变化自动关闭
Sheet组件的内部状态不会在Next.js客户端导航后自动重置,我们可以手动控制Sheet的开关状态,监听路由路径变化来触发关闭操作。
修改MobileNav组件:
"use client"; import React, { useState, useEffect } from "react"; import { Sheet, SheetTrigger, SheetContent } from "./ui/sheet"; import { AlignJustify } from "lucide-react"; import Logo from "./Logo"; import Socials from "./Socials"; import Nav from "./Nav"; import { usePathname } from "next/navigation"; const MobileNav = () => { const [isSheetOpen, setIsSheetOpen] = useState(false); const pathname = usePathname(); // 路由切换时自动关闭Sheet useEffect(() => { setIsSheetOpen(false); }, [pathname]); return ( <div> <Sheet open={isSheetOpen} onOpenChange={setIsSheetOpen}> <SheetTrigger asChild> <AlignJustify className="cursor-pointer" /> </SheetTrigger> <SheetContent> <div className=""> <div className=""> <Logo /> <Nav /> <Socials containerStyles="flex gap-x-4" iconsStyles="text-2xl" /> </div> </div> </SheetContent> </Sheet> </div> ); }; export default MobileNav;
方案二:给每个导航链接包裹SheetClose
如果不想使用受控模式,可以修改Nav组件,让每个导航链接都被SheetClose组件包裹,确保点击链接时触发Sheet关闭:
修改Nav组件:
import { motion } from "framer-motion"; import Link from "next/link"; import { usePathname } from "next/navigation"; import React from "react"; import { SheetClose } from "./ui/sheet"; interface Props { containerStyles?: string; linkStyles?: string; underlineStyles?: string; } const links = [ { path: "/", name: "home" }, { path: "/projects", name: "my projects" }, { path: "/contact", name: "contact" }, ]; const Nav = ({ containerStyles, linkStyles, underlineStyles }: Props) => { const pathName = usePathname(); return ( <nav className={`${containerStyles}`}> {links.map((link, index) => ( <SheetClose asChild key={index}> <Link href={link.path} className={`capitalize ${linkStyles}`} > {link.path === pathName && ( <motion.span initial={{ y: "-100%" }} animate={{ y: 0 }} transition={{ type: "tween" }} layoutId="underline" className={`${underlineStyles}`} /> )} {link.name} </Link> </SheetClose> ))} </nav> ); }; export default Nav;
说明:方案一更可靠,无论通过点击链接还是浏览器前进后退切换路由,Sheet都会自动关闭;方案二则仅在点击导航链接时触发关闭,适合简单场景。
内容的提问来源于stack exchange,提问作者fulvio
相关产品推荐
相关产品推荐

