Next.js中Link锚点跳转URL变化但页面不滚动问题
Next.js同页锚点跳转URL更新但不滚动的修复方案
核心问题排查点
- 自定义组件属性未透传:你直接给
<Section3 id='enews' />传id,但React自定义组件不会自动把props绑定到内部DOM节点上,如果Section3组件内部没有手动接收id并挂载到根元素,页面里实际不存在id为enews的DOM节点,浏览器找不到目标自然不会触发滚动。 - Next.js Link默认滚动逻辑拦截:Next.js 13+ App Router下的Link组件默认行为是跳转后滚动到页面顶部,会覆盖原生锚点的滚动逻辑。
- 滚动容器非根节点:从你的代码结构看存在
bigBody、sections这类多层包裹容器,如果滚动条出现在内部容器而非默认的html/body节点,原生锚点跳转也不会生效。
分步修复
1. 先确认id正确挂载到真实DOM
打开Section3组件文件,将外部传入的id绑定到组件最外层的DOM元素上,示例修改:
// 修改前的Section3 // const Section3 = () => { // return <div className={styles.section3}>/* 区块内容 */</div> // } // 修改后 const Section3 = ({ id }) => { return <div id={id} className={styles.section3}>/* 区块内容 */</div> }
改完打开浏览器开发者工具,在元素面板搜索enews,确认能定位到对应DOM节点再进行下一步。
2. 调整Link组件配置
给Link加上scroll={false}属性,禁用Next.js默认的跳顶部逻辑,让锚点滚动正常触发:
<Link href="#enews" scroll={false}> <div className={styles.buttonContainer}> <Button className={styles.buttonstyle1}>Get started</Button> </div> </Link>
如果配置完还是不触发滚动,直接补一个点击后的手动滚动逻辑,兼容性最好:
<Link href="#enews" scroll={false} onClick={() => { // 等路由状态更新完成后再执行滚动 setTimeout(() => { const targetEl = document.getElementById('enews'); targetEl?.scrollIntoView({ behavior: 'smooth' }); }, 0) }} > <div className={styles.buttonContainer}> <Button className={styles.buttonstyle1}>Get started</Button> </div> </Link>
3. 适配内部滚动容器场景
如果你的页面滚动条是挂载在.bigBody这类内部容器上(可以通过开发者工具看哪个元素出现滚动条确认),需要手动计算偏移量调用容器的滚动方法:
onClick={() => { setTimeout(() => { const targetEl = document.getElementById('enews'); // 替换成你实际的滚动容器选择器 const scrollContainer = document.querySelector('.bigBody'); if (targetEl && scrollContainer) { const targetTop = targetEl.offsetTop - scrollContainer.offsetTop; scrollContainer.scrollTo({ top: targetTop, behavior: 'smooth' }) } }, 0) }}
内容的提问来源于stack exchange,提问作者Mihai INT
相关产品推荐
相关产品推荐

