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

NextJS Link组件锚点跳转异常:跳转至站点根目录而非当前子路径

Next.js Link组件锚点跳转路径错误的原因及解决办法

原因

Next.js 的 Link 组件在处理仅包含锚点(如#data-storage)的 href 属性时,默认会以根路由(/)作为解析基准,而非当前页面所在的路由(/security/)。这就导致点击后跳转到了/#data-storage,而非预期的/security/#data-storage。

而原生<a>标签遵循浏览器默认的URL解析规则,相对锚点会基于当前页面的URL进行解析,因此能正常跳转到当前页面的锚点位置。

解决方案

方法1:使用相对路径拼接锚点

直接在锚点前加上./,让Link基于当前页面的路由解析:

<Link href="./#data-storage" scroll={false}>Data Storage</Link>

方法2:动态拼接当前路径(更灵活)

通过usePathname钩子获取当前页面的路径,再和锚点拼接,适合动态路由等场景:

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

export default function SecurityPage() {
  const currentPath = usePathname();
  return (
    <Link href={`${currentPath}#data-storage`} scroll={false}>Data Storage</Link>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:13:13