在Next.js中,当你希望在路由匹配时改变链接的样式,可以使用 Next.js 提供的 Link
组件与 useRouter
钩子来实现。下面是一个具体的步骤和代码示例:
- 导入必要的模块 - 从
next/link
导入Link
组件,从next/router
导入useRouter
钩子。 - 使用
useRouter
- 在你的组件内部,使用useRouter
钩子得到当前的路由对象。 - 比对路由 - 使用路由对象的
pathname
属性来判断当前路由是否与链接的目标路由匹配。 - 设置样式 - 根据路由是否匹配,动态地应用不同的样式类或样式对象到你的链接元素上。
下面是一个简化的代码示例,展示了如何实现这一过程:
jsximport Link from 'next/link'; import { useRouter } from 'next/router'; export default function NavLink({ href, children }) { // 使用 useRouter 钩子获取当前路由信息 const router = useRouter(); // 检查此链接是否为当前路由,如果是,则设置一个特殊的样式类 const isActive = router.pathname === href; // 根据是否激活来决定样式 const linkStyle = { fontWeight: isActive ? 'bold' : 'normal', color: isActive ? 'green' : 'blue', }; return ( <Link href={href}> <a style={linkStyle}>{children}</a> </Link> ); }
这个 NavLink
组件可以这样使用:
jsxfunction NavigationBar() { return ( <nav> <NavLink href="/">Home</NavLink> <NavLink href="/about">About</NavLink> <NavLink href="/contact">Contact</NavLink> </nav> ); }
在这个例子中,当用户导航到与 NavLink
href
属性相匹配的路由时,链接的样式将变成粗体和绿色。如果不匹配,链接的样式将是普通字体和蓝色。这样可以很直观地向用户展示他们当前所处的页面。
这只是一个简单的样式设置方法。你也可以根据需要将样式类与元素类一起使用,进一步提升样式的复杂度和灵活性。