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

NextJS导航组件无法动态切换当前页激活状态的问题求助

解决NextJS导航组件动态激活状态的问题

问题根源是你硬编码了导航项的current字段,导致状态不会随页面路径变化自动更新。以下根据你使用的NextJS路由方案给出对应解决方法:

方案一:Pages Router(NextJS 12及更早版本)

  1. 引入useRouter钩子获取当前路由信息
  2. 移除导航数组里硬编码的current字段
  3. 动态判断当前路径是否匹配导航项的href

修改后的完整代码:

import { useRouter } from 'next/router'
// 确保你已经导入了对应的图标组件:Squares2X2Icon、UsersIcon、FolderIcon

const navigation = [
    { name: 'Dashboard', href: '/dashboard', icon: Squares2X2Icon },
    { name: 'Orders', href: '/orders', icon: UsersIcon },
    { name: 'Products', href: '/products', icon: FolderIcon },
]

function classNames(...classes) {
    return classes.filter(Boolean).join(' ')
}

const Navigation = () => {
    const router = useRouter()

    return (
        <>
            {navigation.map((item) => {
                // 动态判断当前是否为激活状态
                const isCurrent = router.pathname === item.href
                return (
                    <a
                        key={item.name}
                        href={item.href}
                        className={classNames(
                            isCurrent
                                ? 'bg-gray-100 text-gray-900'
                                : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900',
                            'group flex items-center px-2 py-2 text-sm font-medium rounded-md'
                        )}
                    >
                        <item.icon
                            className={classNames(
                                isCurrent
                                    ? 'text-gray-500'
                                    : 'text-gray-400 group-hover:text-gray-500',
                                'mr-4 flex-shrink-0 h-6 w-6'
                            )}
                            aria-hidden="true"
                        />
                        {item.name}
                    </a>
                )
            })}
        </>
    )
}

export default Navigation

方案二:App Router(NextJS 13+ 应用目录)

  1. 引入usePathname钩子获取当前路径
  2. 同样移除导航数组里的current字段
  3. 动态匹配路径判断激活状态

修改后的完整代码:

import { usePathname } from 'next/navigation'
// 确保你已经导入了对应的图标组件:Squares2X2Icon、UsersIcon、FolderIcon

const navigation = [
    { name: 'Dashboard', href: '/dashboard', icon: Squares2X2Icon },
    { name: 'Orders', href: '/orders', icon: UsersIcon },
    { name: 'Products', href: '/products', icon: FolderIcon },
]

function classNames(...classes) {
    return classes.filter(Boolean).join(' ')
}

const Navigation = () => {
    const pathname = usePathname()

    return (
        <>
            {navigation.map((item) => {
                // 动态判断当前是否为激活状态
                const isCurrent = pathname === item.href
                return (
                    <a
                        key={item.name}
                        href={item.href}
                        className={classNames(
                            isCurrent
                                ? 'bg-gray-100 text-gray-900'
                                : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900',
                            'group flex items-center px-2 py-2 text-sm font-medium rounded-md'
                        )}
                    >
                        <item.icon
                            className={classNames(
                                isCurrent
                                    ? 'text-gray-500'
                                    : 'text-gray-400 group-hover:text-gray-500',
                                'mr-4 flex-shrink-0 h-6 w-6'
                            )}
                            aria-hidden="true"
                        />
                        {item.name}
                    </a>
                )
            })}
        </>
    )
}

export default Navigation

额外说明:嵌套路由激活

如果你的项目有嵌套路由(比如/dashboard/settings),想要父级导航项保持激活状态,可以把判断逻辑改成:

const isCurrent = pathname.startsWith(item.href)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:05:47