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

Next.js路径匹配时激活Link链接?代码问题求助

在Next.js中实现Link组件的激活状态

你代码里的核心问题是函数组件中不能使用this,this.href是无效写法,导致无法匹配当前路径,自然无法添加激活类。下面是可行的解决方法:

基础修复方案

直接将当前路径pathname与Link的href字符串做精确匹配,匹配时添加active类:

function Component() {
  const pathname = usePathname();
  return (
      <div className="links">
        <Link href="/" className={`${pathname === "/" ? "active" : ""}`}>Home</Link>
        <Link href="/store" className={`${pathname === "/store" ? "active" : ""}`}>Store</Link>
        <Link href="/actors" className={`${pathname === "/actors" ? "active" : ""}`}>Actors</Link>
      </div>
  )}

进阶:处理子路由场景

如果访问/store/products这类子路由时,希望/store的Link也保持激活状态,可以用startsWith做前缀匹配:

<Link href="/store" className={`${pathname.startsWith("/store") ? "active" : ""}`}>Store</Link>

封装可复用组件

为了避免重复代码,可以封装一个通用的ActiveLink组件,支持精确匹配和前缀匹配:

import Link from 'next/link';
import { usePathname } from 'next/navigation';

function ActiveLink({ href, children, exact = true }) {
  const pathname = usePathname();
  // 匹配逻辑:exact为true时精确匹配,否则前缀匹配
  const isActive = exact ? pathname === href : pathname.startsWith(href);
  
  return (
    <Link href={href} className={isActive ? "active" : ""}>
      {children}
    </Link>
  );
}

// 使用示例
function Component() {
  return (
      <div className="links">
        <ActiveLink href="/">Home</ActiveLink>
        <ActiveLink href="/store" exact={false}>Store</ActiveLink>
        <ActiveLink href="/actors">Actors</ActiveLink>
      </div>
  )}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:23:28