You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NextUI导航栏的map循环中为激活链接设置isActive属性?

解决NextUI导航栏动态链接的isActive激活问题

针对你用Next.js + NextUI导航栏,动态生成的链接无法单独设置isActive的问题,直接给你两种路由体系下的解决方案:

方案1:Pages Router(传统pages目录)

  1. 先导入useRouter钩子:
import { useRouter } from 'next/router';
  1. 在组件内获取当前路由路径,然后在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目录)

  1. 导入usePathname钩子:
import { usePathname } from 'next/navigation';
  1. 同样在组件内获取路径并做匹配:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:39:37