点击按钮跳转至其他路由页面指定ref区块的实现方法
跨页面跳转至指定区块实现方案
核心逻辑:跨页面跳转时无法直接获取目标页面未挂载组件的ref,需要先完成路由跳转,等home页面完全挂载后,再通过已绑定的ref执行滚动定位。
步骤1:修改首页(localhost路径)页脚按钮的点击事件
根据你使用的React Router版本选择对应跳转写法,跳转时携带需要定位到联系区块的标记即可:
- React Router v6 写法:
import { useNavigate } from 'react-router-dom'; // 页脚组件内部逻辑 const navigate = useNavigate(); const handleContactBtnClick = () => { navigate('/home', { state: { needScrollToContact: true } }); };
- React Router v5 写法:
import { useHistory } from 'react-router-dom'; const history = useHistory(); const handleContactBtnClick = () => { history.push('/home', { needScrollToContact: true }); };
步骤2:在home页面监听路由状态,执行滚动
注意:如果Contact是自定义函数组件,必须用forwardRef把ref透传到组件的根DOM节点上,否则ref.current拿不到真实DOM元素,滚动会失效。
home页面逻辑参考:
import { useEffect, useRef } from 'react'; import { useLocation } from 'react-router-dom'; // 其余组件导入省略 const HomePage = () => { const location = useLocation(); const contactRef = useRef(null); // 你原本绑定给Contact组件的ref(即示例代码里的toto) useEffect(() => { // 校验路由携带的定位标记+ref是否已绑定到DOM if (location.state?.needScrollToContact && contactRef.current) { // 滚动到对应区块,开启平滑滚动效果 contactRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' }); // 清除路由状态,避免页面刷新时重复触发滚动 window.history.replaceState({}, document.title); } }, [location.state]); return ( <div> <Component /> <Component /> <Component /> <Component /> <Contact ref={contactRef} /> </div> ); }; export default HomePage;
更简便的替代方案(hash锚点)
如果不想做路由状态传参,直接用URL hash实现更省事,不需要依赖ref也能生效:
- 按钮跳转逻辑改为
navigate('/home#contact-section') - 给Contact组件的根DOM节点设置id:
<div id="contact-section">...</div> - 浏览器原生就会识别hash自动滚动到对应id的元素位置,需要平滑滚动的话在全局css加
scroll-behavior: smooth即可。
内容的提问来源于stack exchange,提问作者hissroth
相关产品推荐
相关产品推荐

