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

React-Next.js中路由切换时如何将对应导航项的current设为true

Next.js 导航路由动态激活实现方案

你不需要在初始的navigation数组里写死current属性,通过Next.js提供的路由钩子拿到当前页面路径,渲染时动态判断激活状态即可:

步骤1:导入路由钩子

根据你用的Next.js路由模式选择对应钩子:

App Router(Next.js 13+)

// 客户端组件顶部添加,服务端组件无法直接使用客户端钩子
'use client'
import { usePathname } from 'next/navigation'
import classNames from 'classnames'

Pages Router

import { useRouter } from 'next/router'
import classNames from 'classnames'

步骤2:简化导航配置

移除写死的current属性:

const navigation = [
  { name: 'Main', href: '/' },
  { name: 'Test', href: '/test' },
  { name: 'Test 2', href: '#' },
  { name: 'Test 3', href: '#' },
]

步骤3:动态计算激活状态

在组件内拿到当前路径,渲染导航项时对比判断:

App Router 版本

export default function Nav() {
  const pathname = usePathname()

  return (
    <nav>
      {navigation.map((item) => {
        const isCurrent = pathname === item.href
        return (
          <a
            key={item.name}
            href={item.href}
            className={classNames(
              isCurrent ? 'bg-gray-900 text-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white',
              'px-3 py-2 rounded-md text-sm font-medium'
            )}
            aria-current={isCurrent ? 'page' : undefined}
          >
            {item.name}
          </a>
        )
      })}
    </nav>
  )
}

Pages Router 版本

export default function Nav() {
  const router = useRouter()
  const pathname = router.pathname

  return (
    <nav>
      {navigation.map((item) => {
        const isCurrent = pathname === item.href
        return (
          <a
            key={item.name}
            href={item.href}
            className={classNames(
              isCurrent ? 'bg-gray-900 text-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white',
              'px-3 py-2 rounded-md text-sm font-medium'
            )}
            aria-current={isCurrent ? 'page' : undefined}
          >
            {item.name}
          </a>
        )
      })}
    </nav>
  )
}

可选优化

  • 如果需要嵌套路由激活(比如/test/sub路径也激活/test导航项),可以把判断逻辑改成pathname.startsWith(item.href),注意根路径/要单独判断,避免所有路径都命中根导航。
  • 建议将原生a标签替换为Next.js内置的Link组件,避免页面全量刷新,路由切换性能更好,仅需导入Link后替换标签名即可,其他属性无需修改。

内容的提问来源于stack exchange,提问作者Light Yagami

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:54:03