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

React v6锚点问题:页面重载后无法自动滚动至锚点求简易方案

React Router v6 锚点刷新不滚动的简易解决办法

前提准备

确保所有需要锚定的副标题元素都设置了唯一的id属性,比如:

<h2 id="section-about">关于我们</h2>
<h2 id="section-services">服务介绍</h2>

跳转链接使用#加对应id的格式,比如:

<Link to="#section-about">跳转到关于我们</Link>

方案1:监听URL哈希手动触发滚动

这是最直接的解决方式,通过监听路由哈希变化,找到对应元素后执行滚动:

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

function YourPageComponent() {
  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' });
      }
    }
  }, [location.hash]);

  return (
    <div className="page-content">
      {/* 页面内容,包含带id的副标题 */}
      <h2 id="section-about">关于我们</h2>
      <p>...</p>
      <h2 id="section-services">服务介绍</h2>
      <p>...</p>
    </div>
  );
}

如果页面内容是异步加载的(比如从接口获取数据后渲染),需要在数据加载完成后再执行滚动:

// 假设dataLoaded是标记数据是否加载完成的状态
useEffect(() => {
  if (location.hash && dataLoaded) {
    const targetId = location.hash.slice(1);
    const targetElement = document.getElementById(targetId);
    targetElement?.scrollIntoView({ behavior: 'smooth' });
  }
}, [location.hash, dataLoaded]);

方案2:自定义ScrollRestoration组件

React Router v6提供的ScrollRestoration组件默认不处理锚点滚动,我们可以通过自定义getKey方法让它识别哈希变化:

import { ScrollRestoration } from 'react-router-dom';

function CustomScrollRestoration() {
  return (
    <ScrollRestoration
      getKey={(location) => {
        // 将路径和哈希组合作为唯一key,确保哈希变化时触发滚动恢复
        return `${location.pathname}${location.hash}`;
      }}
    />
  );
}

// 在根路由组件中使用
function App() {
  return (
    <BrowserRouter>
      <CustomScrollRestoration />
      {/* 你的路由配置 */}
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </BrowserRouter>
  );
}

这个方案更贴合React Router的生态,适合需要统一管理页面滚动行为的项目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:05:18