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

Next.js 使用Link与router为当前页面设置active类名的疑问

实现错误原因
  • 存在低级笔误:判断逻辑中误用了projects.id,你遍历的是单个项目对象,正确取值应为project.id
  • 核心逻辑错误:Next.js 框架中router.pathname返回的是路由文件的定义模式,比如你的动态路由文件是pages/projects/[id].js,该属性返回值固定为/projects/[id],和实际访问的带具体ID的路径完全不匹配,所以原有逻辑永远不会触发激活态。
可用修复方案

方案1:用router.asPath匹配实际路径

router.asPath返回的是浏览器地址栏中展示的真实访问路径,直接用该属性匹配即可,修正后代码如下:

<Link href={`/projects/${project.id}`}>
  <a
    className={router.asPath === `/projects/${project.id}` ? "active" : ""}
  >
    {project.title}
  </a>
</Link>

如果你的路由存在带查询参数的场景,可以用router.asPath.split('?')[0]截取纯路径部分后再匹配,避免参数干扰判断。

方案2:用动态路由参数匹配

如果你确定当前页面处于/projects/[id]路由下,也可以直接用路由参数匹配:

<Link href={`/projects/${project.id}`}>
  <a
    className={router.query.id === project.id ? "active" : ""}
  >
    {project.title}
  </a>
</Link>
更优的通用方案

可以封装全局通用的激活链接组件,避免每次写重复的判断逻辑:

import { useRouter } from 'next/router'
import Link from 'next/link'

const ActiveLink = ({ href, children, activeClass = 'active' }) => {
  const router = useRouter()
  // 截取纯路径做匹配
  const currentPath = router.asPath.split('?')[0]
  const isActive = currentPath === href
  return (
    <Link href={href}>
      <a className={isActive ? activeClass : ''}>
        {children}
      </a>
    </Link>
  )
}

// 业务中使用方式
<ActiveLink href={`/projects/${project.id}`}>
  {project.title}
</ActiveLink>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:54:03