Next.js实现点击滚动到指定页面区段的可用依赖包及方案问询
Next.js导航点击滚动到对应区段解决方案
你提到的react-scroll完全可以在Next.js中正常运行,不存在适配问题,以下是两种可直接落地的方案:
方案1:使用react-scroll实现
步骤1:安装依赖
npm install react-scroll # 或者 yarn add react-scroll
如果使用的是Next.js 13+的App Router,需要在FeaturedProductHeader组件顶部添加'use client'指令,标记为客户端组件。
步骤2:修改导航项代码
导入react-scroll的Link组件,替换原有静态li:
import { Link as ScrollLink } from 'react-scroll' // 原有代码不变,修改ul部分: <ul className={classes['headerList']} > <li > <ScrollLink to="section1" // 对应页面对应区段的id值 smooth={true} // 开启平滑滚动 duration={500} // 滚动动画时长,单位ms offset={-80} // 偏移量,通常设置为导航栏高度,避免内容被固定导航挡住 > {props.link1} </ScrollLink> </li> <li> <ScrollLink to="section2" smooth={true} duration={500} offset={-80} > {props.link2} </ScrollLink> </li> <li> <ScrollLink to="section3" smooth={true} duration={500} offset={-80} > {props.link3} </ScrollLink> </li> </ul>
步骤3:给页面对应区段设置匹配id
<div id="section1">第一区段内容</div> <div id="section2">第二区段内容</div> <div id="section3">第三区段内容</div>
方案2:原生JS实现(无额外依赖)
如果不想引入第三方包,可以直接用浏览器原生scrollIntoViewAPI实现,更轻量:
步骤1:添加滚动处理函数
const FeaturedProductHeader = (props) => { const scrollToSection = (sectionId) => { document.getElementById(sectionId)?.scrollIntoView({ behavior: 'smooth', // 平滑滚动 block: 'start' // 滚动到区段顶部 }) } // 原有代码不变
步骤2:给导航项绑定点击事件
<ul className={classes['headerList']} > <li onClick={() => scrollToSection('section1')}>{props.link1}</li> <li onClick={() => scrollToSection('section2')}>{props.link2}</li> <li onClick={() => scrollToSection('section3')}>{props.link3}</li> </ul>
同样需要给页面对应区段设置匹配的id即可,该方案适配所有Next.js版本。
内容的提问来源于stack exchange,提问作者MarkoC
相关产品推荐
相关产品推荐

