使用react-scroll时如何避免组件被NavBar遮挡?
解决react-scroll滚动被固定导航栏遮挡的问题
我使用react-scroll实现四个组件的平滑滚动,点击NavBar中的组件链接时,组件会滚动到屏幕顶部而非NavBar底部,导致部分信息被遮挡。我的NavBar是sticky固定在顶部的,每个组件高度设为h-screen,使用TailwindCSS。
NavBar代码
<nav className="sticky z-10 top-0 font-semibold text-xl bg-nature-green grid grid-cols-3 items-center"> <a href="home" className="flex no-underline text-black"> <img className="h-8 w-8 " src="https://www.freeiconspng.com/thumbs/letter-j-icon-png/letter-j-icon-png-26.png" /> <span>BRAND</span> </a> <div className="flex sm:justify-center space-x-8 "> {[ ["Home", "home"], ["About", "about"], ["Products", "products"], ["Find Us", "find"], ].map(([title, url]) => ( <Link to={url} spy={true} smooth={true} className="p-3 focus:bg-clicked-green hover:bg-selected-green no-underline text-black" > {title} </Link> ))} </div> <div className="flex space-x-8 justify-end"> {[twitter, twitter, instagram, instagram].map((icon) => ( <a> <img className="h-w right-0" src={icon} /> </a> ))} </div> </nav>
解决方案
1. 给react-scroll的Link添加offset属性
react-scroll的Link组件支持offset参数,设置为导航栏高度的负值,就能让滚动位置停在导航栏下方。比如导航栏高度是64px(对应Tailwind的h-16),就设置offset={-64}:
<Link to={url} spy={true} smooth={true} offset={-64} // 根据导航栏实际高度调整数值 className="p-3 focus:bg-clicked-green hover:bg-selected-green no-underline text-black" > {title} </Link>
2. 使用CSS scroll-margin-top属性
给每个滚动目标组件添加scroll-margin-top样式,值等于导航栏高度。用Tailwind可以直接写scroll-mt-[64px]:
<div id="home" className="h-screen scroll-mt-[64px]"> {/* 组件内容 */} </div>
这个方法无需修改react-scroll的配置,纯CSS实现,兼容性也不错。
3. 动态获取导航栏高度(适配响应式)
如果导航栏在不同屏幕尺寸下高度变化,用JavaScript动态获取高度:
- 给导航栏添加ref:
import { useRef } from 'react'; const NavBar = () => { const navRef = useRef(null); const navHeight = navRef.current?.offsetHeight || 0; return ( <nav ref={navRef} className="sticky z-10 top-0 font-semibold text-xl bg-nature-green grid grid-cols-3 items-center"> {/* 导航栏内容 */} <div className="flex sm:justify-center space-x-8 "> {[ ["Home", "home"], ["About", "about"], ["Products", "products"], ["Find Us", "find"], ].map(([title, url]) => ( <Link to={url} spy={true} smooth={true} offset={-navHeight} className="p-3 focus:bg-clicked-green hover:bg-selected-green no-underline text-black" > {title} </Link> ))} </div> </nav> ) }
这样不管导航栏高度怎么变,滚动偏移都会自动适配。
内容的提问来源于stack exchange,提问作者user21075278
相关产品推荐
相关产品推荐

