如何在NextUI导航栏的map循环中为激活链接设置isActive属性?
解决NextUI导航栏动态链接的isActive激活问题
针对你用Next.js + NextUI导航栏,动态生成的链接无法单独设置isActive的问题,直接给你两种路由体系下的解决方案:
方案1:Pages Router(传统pages目录)
- 先导入
useRouter钩子:
import { useRouter } from 'next/router';
- 在组件内获取当前路由路径,然后在map循环里做匹配:
const router = useRouter(); // ... <Navbar.Content enableCursorHighlight activeColor="primary" hideIn="xs" variant="highlight-rounded" > {navigation.map((item, index) => ( <Navbar.Link key={index} href={item.link} // 对比当前路由路径和链接href,匹配则激活 isActive={router.pathname === item.link} > {item.title} </Navbar.Link> ))} </Navbar.Content>
方案2:App Router(app目录)
- 导入
usePathname钩子:
import { usePathname } from 'next/navigation';
- 同样在组件内获取路径并做匹配:
const pathname = usePathname(); // ... <Navbar.Content enableCursorHighlight activeColor="primary" hideIn="xs" variant="highlight-rounded" > {navigation.map((item, index) => ( <Navbar.Link key={index} href={item.link} isActive={pathname === item.link} > {item.title} </Navbar.Link> ))} </Navbar.Content>
额外说明
如果你的链接包含动态参数(比如/post/[id]),可以用更灵活的匹配方式,比如判断当前路径是否以item.link开头:
// 示例:匹配所有/post开头的路径 isActive={pathname.startsWith(item.link)}
或者用router.asPath(Pages Router)来匹配完整的URL路径(包含参数)。
这样就能实现只有当前路由对应的导航链接才会被设置为激活状态,完美适配后端返回的动态导航列表。
内容的提问来源于stack exchange,提问作者Mintee
相关产品推荐
相关产品推荐

