Next.js中react-scroll与Tailwind overflow-y-scroll冲突问题
解决Tailwind滚动吸附与react-scroll跳转冲突的问题
问题核心:react-scroll默认监听window的滚动事件,但你的滚动容器是内部带overflow-y-scroll的<div>,导致Link组件找不到正确的滚动目标,跳转失效。
直接按以下方法修改代码即可解决:
修改后的完整代码
'use client' import Image from 'next/image' import { Link } from 'react-scroll' import { useRef } from 'react' export default function Home() { // 创建滚动容器的引用 const scrollContainerRef = useRef(null) return ( <main> {/* 将ref绑定到滚动容器 */} <div ref={scrollContainerRef} className='snap-y snap-mandatory h-screen w-screen overflow-y-scroll'> <div className="snap-start bg-beige h-screen"> <div className='flex justify-between pl-3 pr-3'> <div className='relative h-14 w-14 md:h-16 md:w-16'> <Image src="/logo-gray.png" layout="fill" objectFit="cover" alt="Logo" /> </div> <div className='flex items-center'> {/* 给每个Link指定滚动容器 */} <h5 className='p-4' style={{ cursor: 'pointer' }}> <Link to="about" spy={true} smooth={true} duration={800} container={scrollContainerRef} >about</Link> </h5> <h5 className='p-4' style={{ cursor: 'pointer' }}> <Link to="services" spy={true} smooth={true} duration={800} container={scrollContainerRef} >services</Link> </h5> <h5 className='p-4' style={{ cursor: 'pointer' }}> <Link to="my-work" spy={true} smooth={true} duration={800} container={scrollContainerRef} >my work</Link> </h5> <h5 className='p-4' style={{ cursor: 'pointer' }}> <Link to="contact" spy={true} smooth={true} duration={800} container={scrollContainerRef} >contact</Link> </h5> </div> </div> </div> <div className="snap-start bg-gray h-screen" id='about'> </div> <div className="snap-start bg-beige h-screen" id='services'> </div> <div className="snap-start bg-gray h-screen" id='my-work'> </div> <div className="snap-start bg-beige h-screen" id='contact'> </div> </div> </main> ); }
关键改动说明
- 引入
useRef创建滚动容器的引用,绑定到带overflow-y-scroll的容器上 - 给每个
react-scroll的Link组件添加container={scrollContainerRef}属性,明确告诉它要在指定容器内完成滚动跳转
这样Tailwind的滚动吸附功能可以正常工作,同时react-scroll的跳转也能准确定位到目标区块。
内容的提问来源于stack exchange,提问作者Stefany
相关产品推荐
相关产品推荐

