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

React应用点击首页卡片后,如何在新渲染服务页滚动到对应元素?

解决React跨页面点击后自动滚动到指定元素的方案

1. 修改首页卡片的导航逻辑

确保点击卡片时,导航路径带上目标服务模块的ID作为URL hash,同时避免a标签和navigate的跳转冲突:

const navigate = useNavigate()

return (
    <div id={data.id} className="serviceCard slideUpContainer" onClick={() => navigate(`${data.link}#${data.id}`)}>
        <img src={require('../visuals/' + data.img + '.png')} alt={data.title} />
        <div className="slideUpContent">
            <h2 className="slideUpTitle">{data.title}</h2>
            <p className="slideUpText">{data.excerpt}</p>
            <div className="linkContainer">
                <span onClick={(e) => {
                    e.stopPropagation();
                    navigate(`${data.link}#${data.id}`);
                }}>{data.btn}<i className="glyphicon glyphicon-menu-right"></i></span>
            </div>
        </div>
    </div>
)

2. 在服务页面实现滚动逻辑

在包含所有Service子组件的父页面中,通过useEffect监听组件挂载和URL hash变化,自动定位到目标元素:

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

const ServicesPage = () => {
    const location = useLocation();

    useEffect(() => {
        const targetId = location.hash.slice(1);
        if (targetId) {
            const targetElement = document.getElementById(targetId);
            if (targetElement) {
                // 平滑滚动到目标元素,可调整参数控制滚动行为
                targetElement.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        }
    }, [location.hash]);

    return (
        <div className="services-page">
            {/* 渲染各个Service子组件,确保每个组件的data.id与首页卡片的data.id一致 */}
            <Service data={service1Data} />
            <Service data={service2Data} />
            {/* ...其他服务组件 */}
        </div>
    );
};

export default ServicesPage;

3. 核心注意事项

  • 必须保证首页卡片的data.id和对应服务模块的data.id完全匹配,否则无法定位到目标元素。
  • React Router v6默认不会自动处理跨页面锚点滚动,因此需要手动通过scrollIntoView实现。
  • 若保留a标签,需添加e.preventDefault()阻止默认跳转行为,避免和navigate逻辑冲突。
  • 可根据需求调整scrollIntoView的参数,比如将behavior设为auto实现瞬间滚动,或block设为center让目标元素居中显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:52:43