动态路由下如何检测激活路径,实现导航按钮高亮?
导航栏Projects按钮在含Slug路径下的高亮修复方案
当前问题:访问/projects/slug-name这类带有动态Slug的项目路径时,导航栏中的「Realizacje」(对应/projects路径的按钮)无法触发高亮效果。原激活判断逻辑const active = path === href仅在路径完全匹配时生效,导致带Slug的子路径无法识别为/projects的活跃状态。
解决方案
修改LinkItem组件中的激活状态判断逻辑,新增路径前缀匹配处理,同时避免根路径/误匹配所有子路径:
// 替换原active判断行 const active = path === href || (href !== "/" && path.startsWith(href));
逻辑说明
- 保留原有的完全匹配逻辑,确保直接点击导航项时正常高亮
- 新增前缀匹配:当
href不是根路径/时,判断当前path是否以href开头,这样/projects/xxx会匹配/projects - 排除根路径的前缀匹配,避免所有路径都触发首页按钮高亮
修改后的完整组件代码
LinkItem组件
const LinkItem = ({ href, path, target, children, ...props }) => { // 修改激活判断逻辑 const active = path === href || (href !== "/" && path.startsWith(href)); const inactiveColor = useColorModeValue("gray200", "whiteAlpha.900"); const bgColor = useColorModeValue("#F7F2F2", "#21262D"); const textColor = useColorModeValue("gray.900", "gray.100"); return ( <NextLink href={href} passHref scroll={false}> <Link p="4px" pl={3} pr={3} rounded="3xl" bg={active ? bgColor : undefined} color={active ? textColor : inactiveColor} target={target} style={{ textDecoration: "none" }} transition="1000ms" {...props} > {children} </Link> </NextLink> ); };
Navbar组件(无需修改)
const Navbar = (props) => { const borderColor = useColorModeValue("#EDE9E9", "gray.800"); const backgroundColor = useColorModeValue("#EDE9E9", "#090C10"); const { path } = props; console.log(path); return ( <Box as="nav" {...props} mt="8px"> <Container maxW="2xl"> <Flex gap="4" align="center" minWidth="max-content"> <Box> <Heading size="md"> <IoWaterOutline size={28} color="#07344D" /> </Heading> </Box> <Spacer /> <Box bg={backgroundColor} rounded="3xl"> <Stack direction="row" display={{ base: "none", md: "flex" }} width={{ base: "full", md: "auto" }} alignItems="center" border="2px" borderColor={borderColor} rounded="3xl" p={1} > <LinkItem href="/" path={path}> Strona główna </LinkItem> <LinkItem href="/about" path={path}> O firmie </LinkItem> <LinkItem href="/projects" path={path}> Realizacje </LinkItem> <LinkItem href="/contact" path={path}> Kontakt </LinkItem> </Stack> </Box> </Flex> </Container> </Box> ); };
内容的提问来源于stack exchange,提问作者xxxbud
相关产品推荐
相关产品推荐

