NextJS导航组件无法动态切换当前页激活状态的问题求助
解决NextJS导航组件动态激活状态的问题
问题根源是你硬编码了导航项的current字段,导致状态不会随页面路径变化自动更新。以下根据你使用的NextJS路由方案给出对应解决方法:
方案一:Pages Router(NextJS 12及更早版本)
- 引入
useRouter钩子获取当前路由信息 - 移除导航数组里硬编码的
current字段 - 动态判断当前路径是否匹配导航项的
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+ 应用目录)
- 引入
usePathname钩子获取当前路径 - 同样移除导航数组里的
current字段 - 动态匹配路径判断激活状态
修改后的完整代码:
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
相关产品推荐
相关产品推荐

