react-scroll的Link标签无跳转目标,页面平滑滚动功能失效求助
React Scroll Link 无法生效的解决方案
问题根源
你的代码存在两个核心问题:
- 目标ID不匹配:
react-scroll的Link指定跳转目标为"sec",但Secondpanel组件中没有对应id="sec"的元素,当前仅存在id="home",导致找不到跳转目标。 - 滚动容器结构错误:三个面板组件被嵌套在同一个
h-screen的div内,每个面板自身又设置了h-screen,导致所有面板堆叠在同一屏幕高度内,滚动容器无法识别到第二个面板的位置,同时原生snap属性和react-scroll的滚动逻辑也产生了冲突。
修复步骤
1. 修正目标ID与跳转指向的匹配
修改Secondpanel组件,将section的id改为"sec",与Link的to属性值一致:
import React, {Component} from 'react'; class Secondpanel extends Component { render() { return ( <section id="sec" className="snap-start bg-dark-grey h-screen w-screen"> <h1>Hi Paul</h1> </section> ); } } export default Secondpanel;
2. 调整滚动容器结构
修改Site组件,将三个面板直接放在滚动容器内,避免嵌套导致的高度堆叠问题,同时为滚动容器添加ID,明确react-scroll的作用范围:
import React, {Component} from 'react'; import Firstpanel from "./firstpanel"; import Secondpanel from "./secondpanel"; import Thirdpanel from "./thirdpanel"; class Site extends Component { render() { return ( <div id="scroll-container" className="h-screen snap-y snap-mandatory overflow-x-hidden overflow-y-auto"> <div className="snap-start bg-[url('../public/images/banner_cropped.png')] bg-dark-grey bg-blend-multiply bg-[length:100vw_100vh] h-screen w-screen "> <Firstpanel></Firstpanel> </div> <Secondpanel></Secondpanel> <Thirdpanel></Thirdpanel> </div> ); } } export default Site;
3. 完善Link组件配置
在Firstpanel的Link中添加containerId属性,指定滚动容器,确保react-scroll能正确识别滚动范围:
import React, {Component} from 'react'; import {Link} from "react-scroll"; class Firstpanel extends Component { render() { return ( <section className="w-screen h-screen flex justify-center items-center flex-col gap-20"> <h1 className="font-bold text-8xl text-beige select-none">Welcome to the coding world!</h1> <p className="font-bold text-4xl text-beige select-none">This site is going to be my personal portfolio for future projects</p> <Link className="w-16 h-16 rounded-full mt-12 animate-bounce" to="sec" spy={true} smooth={true} containerId="scroll-container" > <div className="rounded-full w-16 h-16 bg-[url('../public/images/second_white_arrow_down.png')] bg-cover cursor-pointer"></div> </Link> </section> ); } } export default Firstpanel;
额外说明
- 确保你安装的
react-scroll版本为稳定版(建议v3.x及以上),避免版本兼容问题。 - 原生的
snap属性可以保留,但需要确保它和react-scroll的滚动逻辑不冲突,上述结构调整后两者可以共存。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

