如何在Next.JS中使用styled-components实现激活态链接
Next.js导航栏激活态链接实现方案
Next.js官方确实没有在Link组件内置类似react-router-dom的activeClass属性,可通过封装自定义组件实现对应功能,以下分别对应两种路由模式的实现方案:
方案1:适用于App Router(Next.js 13+ 版本默认路由模式)
- 基于Next.js内置的
usePathnameHook判断当前页面路径,和链接href属性匹配时添加激活样式 - 注意:App Router下使用该组件需要在文件顶部添加
'use client'指令标识为客户端组件
自定义激活态链接组件代码
// components/ActiveLink.tsx 'use client'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; interface ActiveLinkProps { href: string; children: React.ReactNode; activeClass: string; normalClass?: string; } export default function ActiveLink({ href, children, activeClass, normalClass = '' }: ActiveLinkProps) { const pathname = usePathname(); // 完全匹配路径 const isActive = pathname === href; // 若需要子路径也激活父级导航,可替换为以下逻辑(根路径单独处理) // const isActive = href === '/' ? pathname === href : pathname.startsWith(href); return ( <Link href={href} className={isActive ? `${normalClass} ${activeClass}` : normalClass}> {children} </Link> ); }
导航栏调用示例
// components/Navbar.tsx import ActiveLink from './ActiveLink'; export default function Navbar() { return ( <nav className="flex gap-6 p-4 border-b"> <ActiveLink href="/" normalClass="text-gray-500 hover:text-gray-700" activeClass="text-blue-600 font-bold" > 首页 </ActiveLink> <ActiveLink href="/projects" normalClass="text-gray-500 hover:text-gray-700" activeClass="text-blue-600 font-bold" > 项目 </ActiveLink> <ActiveLink href="/about" normalClass="text-gray-500 hover:text-gray-700" activeClass="text-blue-600 font-bold" > 关于 </ActiveLink> </nav> ); }
方案2:适用于Pages Router(Next.js 12及更早版本默认路由模式)
- 基于
useRouterHook获取当前路径判断激活态即可
自定义激活态链接组件代码
// components/ActiveLink.tsx import { useRouter } from 'next/router'; import Link from 'next/link'; interface ActiveLinkProps { href: string; children: React.ReactNode; activeClass: string; normalClass?: string; } export default function ActiveLink({ href, children, activeClass, normalClass = '' }: ActiveLinkProps) { const router = useRouter(); const isActive = router.pathname === href; return ( <Link href={href} className={isActive ? `${normalClass} ${activeClass}` : normalClass}> {children} </Link> ); }
调用方式和App Router场景完全一致。
内容的提问来源于stack exchange,提问作者zhyp
相关产品推荐
相关产品推荐

