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

React Router v6跳转后无法定位指定HTML标签问题求助

React Router v6 跳转后滚动到指定锚点的解决方法

问题原因

你在路由path中写/mypage/#c是错误的——哈希部分(#及后面的内容)不属于路由路径的一部分,React Router不会匹配这种格式的路径,因此跳转后仅加载了MyPage组件,但没有处理哈希对应的滚动逻辑。

正确实现步骤

1. 修正路由配置

路由只需要定义页面路径,无需包含哈希:

<Route path="/mypage" element={<MyPage />} />

2. 跳转时携带哈希参数

使用Link组件或useNavigate钩子跳转时,直接在目标路径后拼接哈希:

  • 用Link组件:
<Link to="/mypage#c">跳转到MyPage的指定位置</Link>
  • 用useNavigate钩子:
import { useNavigate } from 'react-router-dom';

const navigate = useNavigate();
// 触发跳转
navigate('/mypage#c');

3. 在目标组件中处理滚动

React Router v6默认不会自动处理哈希滚动,需要在MyPage组件中监听路径变化,主动滚动到目标元素:

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

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

  useEffect(() => {
    // 检查是否存在哈希
    if (location.hash) {
      // 移除哈希前缀#,获取目标元素ID
      const targetId = location.hash.slice(1);
      const targetElement = document.getElementById(targetId);
      
      if (targetElement) {
        // 滚动到目标元素,可配置平滑滚动
        targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }
  }, [location]);

  return (
    <div>
      {/* 页面其他内容 */}
      <div id="c">这是需要滚动到的目标标签</div>
    </div>
  );
}

补充说明

  • 页面刷新后,上述useEffect逻辑依然有效,因为刷新时location.hash会被保留。
  • scrollIntoView的配置项可按需调整,比如block: 'center'可以让目标元素居中显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:15:49