首页 > 解决方案 > Javascript/React:当兄弟组件/div 的高度发生变化时,window.scrollY 滚动时的像素数随机变化。为什么?

问题描述

我希望导航栏在向上滚动时保持粘性,而在使用 React 向下滚动时不保持粘性。我添加了以下代码,它工作正常。问题如下:另一个组件(不是嵌套的兄弟组件)根据滚动事件更改其高度。不知何故,当高度发生变化时(向下滚动时会变小),这会影响滚动像素数。因此,当我开始滚动时window.scrollY为 0 并且滚动的次数越多,它增加的次数就越多(全部正确)。但是,当同级组件的高度发生变化时,它会发生变化(假设window.scrollY是 400,突然之间没有我向上滚动它会恢复到 250)。我不知道为什么兄弟 div 的高度会影响另一个 divs window.scrollY。有任何想法吗?谢谢!

const App = () => {
  const [sticky, setSticky] = React.useState(false)
  const [lastScroll, setLastScroll] = React.useState(0)

    const handleScroll = () => {
    let currentScroll = window.scrollY

    if (currentScroll <= lastScroll) {
      setSticky(true)
    } else {
      setSticky(false)
    }
    setLastScroll(currentScroll)
  }

  React.useEffect(() => {
    document.addEventListener("scroll", handleScroll)
    return () => {
      document.removeEventListener("scroll", handleScroll)
    }
  })
  return (
    <div>
      <nav className={`menu-container ${sticky ? "sticky" : ""}`}>
        <div className="menu-wrapper">
          <p>home</p>
            <p>shop</p>  
          <p>user</p>
        </div>
      </nav>
      <div>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem 
            Ipsum has been  more recently with desktop publishing software like Aldus 
            PageMaker including versions of Lorem Ipsum.</p>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when 
            an  unknown printer ersions of Lorem Ipsum.</p>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when 
            an unknown printer tons of Lorem Ipsum.</p>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
            Lorem Ipsum haons of Lorem Ipsum.</p>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
            Lorem Ipsum  and more recently with
        </p>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when 
            rinter took a galley of type and scrambled it to make a type specimen book. It has 
        </p>
      </div>
    </div>
  )
}

标签: javascriptreactjsscroll

解决方案


推荐阅读