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

Next.js 13 App目录如何获取当前pathname?实现导航高亮

Next.js 13 App Router 中高亮当前导航链接的解决方案

在Next.js 13的App Router模式下,next/navigation提供的useRouter确实不再包含pathname属性,要实现当前导航链接的高亮,你可以使用以下两种方案:

方案一:使用 usePathname 钩子(推荐)

usePathname 是App Router专门用于获取当前URL路径名的钩子,直接替换原来的router.pathname逻辑即可:

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

const StyledNavLink: React.FC<NavLinkProps> = ({ to, children }) => {
  const pathname = usePathname();
  
  // 基础匹配:严格相等判断当前路径是否等于导航链接地址
  const isActive = pathname === to;
  
  // 可选:支持子路由匹配(比如"/blog"匹配"/blog/123")
  // const isActive = to === "/" ? pathname === "/" : pathname.startsWith(to);

  return (
    <Link href={to} className={getNavLinkClass({ isActive })}>
      {children}
    </Link>
  );
};

说明

  • usePathname 返回当前页面的完整路径(例如访问/about时返回"/about"),可以直接和导航链接的to属性做严格匹配。
  • 如果需要让父路由链接在子路由页面也保持高亮,可以调整匹配逻辑为startsWith,同时单独处理根路径"/"的特殊情况,避免所有页面都高亮根链接。

方案二:使用 useSelectedLayoutSegments(适合嵌套导航)

如果你的导航是嵌套布局的一部分,可以用useSelectedLayoutSegments获取当前布局下的路由分段数组,用于更精细的导航匹配:

import Link from "next/link";
import { useSelectedLayoutSegments } from 'next/navigation';

const StyledNavLink: React.FC<NavLinkProps> = ({ to, children }) => {
  const segments = useSelectedLayoutSegments();
  // 例如to为"/blog"时,segments[0] === "blog"时判定为活跃
  const isActive = segments[0] === to.slice(1); // 去掉路径开头的"/"

  return (
    <Link href={to} className={getNavLinkClass({ isActive })}>
      {children}
    </Link>
  );
};

说明

  • useSelectedLayoutSegments 返回当前布局层级下的路由分段数组(例如访问/blog/post-1时,根布局下返回["blog", "post-1"],blog布局下返回["post-1"]),适合多层嵌套导航的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:10:13