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

react-router-dom中Link组件跳转#id锚点失效如何解决

react-router 的 Link 组件核心功能是处理单页应用的内部路由跳转,默认没有继承原生 <a> 标签的锚点滚动行为,所以直接写 to='#about' 不会触发滚动,可根据使用场景选择以下方案解决:

场景1:同页面内的锚点跳转

直接在 Link 上绑定点击事件手动触发滚动即可:

<Link
  to=""
  onClick={(e) => {
    e.preventDefault();
    document.getElementById('about')?.scrollIntoView({
      behavior: 'smooth' // 不需要平滑滚动可以删掉该配置
    });
  }}
>
  跳转到关于区块
</Link>

场景2:跨页面的锚点跳转(从其他页面跳转到指定页面的锚点位置)

步骤1:编写跳转的Link代码

把哈希值通过 to 参数的对象形式传入:

<Link to={{ pathname: '/目标页面路由', hash: '#about' }}>跳转到关于页</Link>

步骤2:在目标页面监听哈希变化触发滚动

在目标页面组件内加如下逻辑:

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function AboutPage() {
  const location = useLocation();

  // 监听路由变化,匹配到哈希就滚动到对应元素
  useEffect(() => {
    if (location.hash) {
      const targetId = location.hash.slice(1);
      const targetEl = document.getElementById(targetId);
      targetEl?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [location]);

  return <div id="about">关于区块内容</div>
}

全局统一处理方案

如果项目里锚点跳转的场景很多,可以在路由根组件统一加监听逻辑,不用每个链接单独适配:

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();

  useEffect(() => {
    if (location.hash) {
      const targetId = location.hash.slice(1);
      // 加延迟避免DOM未渲染完成找不到元素
      setTimeout(() => {
        document.getElementById(targetId)?.scrollIntoView({ behavior: 'smooth' });
      }, 100);
    }
  }, [location]);

  return {/* 你的路由组件内容 */}
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:57:00