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

React跨页面点击链接跳转首页并滚动到指定div的实现方案

解决React跨页跳转首页并滚动到指定Section的问题

问题核心

跨页面点击Link跳转首页时,/#sectionX的hash方式仅在首页内有效,本质是React Router跨页跳转后首页组件重新挂载,默认不会自动解析hash并触发滚动行为。

可行方案

方案1:监听URL Hash实现滚动

在Homepage组件中通过useLocation钩子监听URL的hash变化,组件挂载或hash更新时自动滚动到对应元素。

步骤1:给Section组件添加对应id

确保每个Section的根元素设置匹配的id:

// Section1组件示例
function Section1() {
  return <div id="section1">...</div>;
}

步骤2:修改Homepage组件监听hash

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

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

  useEffect(() => {
    if (location.hash) {
      const targetElement = document.querySelector(location.hash);
      if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth' }); // 平滑滚动,可移除改为即时滚动
      }
    }
  }, [location.hash]);

  return (
    <>
      <Section1 />
      <Section2 />
      <Section3 />
      ...
    </>
  );
}

导航的Link保持原有写法即可:

<Link className={Style.header__link} to="/#section1">About</Link>

方案2:通过路由state传递滚动目标

不依赖URL hash,通过Link的state参数传递滚动目标标识,在Homepage中处理滚动。

步骤1:修改导航的Link

<Link 
  className={Style.header__link} 
  to={{ 
    pathname: '/', 
    state: { scrollTo: 'section1' } 
  }}
>
  About
</Link>

步骤2:在Homepage中监听state

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

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

  useEffect(() => {
    const { scrollTo } = location.state || {};
    if (scrollTo) {
      const targetElement = document.getElementById(scrollTo);
      if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth' });
      }
    }
  }, [location.state]);

  return (
    <>
      <Section1 />
      <Section2 />
      <Section3 />
      ...
    </>
  );
}

注意事项

  • 两种方案都需要确保目标Section的根元素存在对应id,否则无法定位元素。
  • 若需兼容旧浏览器,可移除behavior: 'smooth'参数,使用默认即时滚动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:43:31