javascript - 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>
)
}
解决方案
推荐阅读
- python - 文件上传的 Sanic 单元测试
- sql - 我是 laravel 的新手,我想根据部门加入两个表。我想如何在下面给出
- c - 我只是读了指针和数组地址算术。但我已经搞混了
- ruby-on-rails - 使用脚手架建表成功后无法添加列
- python - 根据 Django 中的自定义用户类型限制对视图的访问
- python - 如何在 python 项目中使用 unitest?
- multithreading - 为什么计算着色器线程在移动设备上随机失败,而不是在 PC 上?
- swift - 尝试显示数据库中的图片时出现致命错误
- amcharts4 - 无法使用导出 API 使用 Amcharts4 导出 png
- apache-spark - 如何根据列值选择列?