You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React导航栏滚动200px后无法粘滞,handle函数调用是否有误?

问题分析与解决方案

你的handle函数调用本身没问题,导航栏不粘滞的核心原因是Tailwind的sticky类需要配合top属性才能生效,单纯加sticky类浏览器不知道该把元素粘在哪个位置。

修改步骤:

  • 把导航栏外层div的className改成:${stickyShow? 'sticky top-0':'relative'},加上top-0让元素粘在页面顶部
  • (可选优化)handle函数可以简化,不用写if-else:
    const handle = () => setStickyShow(window.scrollY > 200)
    

修改后的完整代码:

import React,{useState,useEffect} from 'react'

function Nav() {
    const [stickyShow,setStickyShow]=useState(false)
    useEffect(() => {
      window.addEventListener('scroll', handle)
      return () => {
        window.removeEventListener('scroll', handle);
      }
    }, [])
    const handle=()=>{
        setStickyShow(window.scrollY > 200)
    }
    
    const item=[
        {h1:'Home'},
        {h1:'New'},
        {h1:'Blog'},
        {h1:'About us'},
    ]
  return (
    <div>
        <div className={`${stickyShow? 'sticky top-0':'relative'}`}>
        <div className='px-2 py-2 bg-slate-400'>
            <ul className='flex justify-between'>
            {item.map((val,i)=>{
                return <li key={i}>
                    {val.h1}
                </li>
            })}
            </ul>
        </div>
        </div>
        <div className='h-[800px] bg-red-300'>
x   
        </div>
    </div>
    
  )
}   

export default Nav

核心原因说明:

CSS中position:sticky的生效逻辑是:当元素滚动到指定的偏移位置(比如top:0)时,才会从相对定位切换为固定定位。Tailwind的sticky类只设置了position:sticky,没有默认的偏移值,所以必须手动添加top-0来触发粘滞效果。

内容的提问来源于stack exchange,提问作者Safal Thapa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 01:19:52