【发布时间】:2022-12-03 23:28:49
【问题描述】:
我目前正在尝试创建一段代码,当用户滚动经过某个地方时,该代码将设置一个 div 模式。为此,我使用了window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection)),其中我传递了从React.useState(0) 返回的两个变量,然后在事件侦听器中检查window.scrollY 属性是否大于scrollSection 状态中的值,如果所以用js翻译吧。但无论我做什么,提供的更新状态的功能都不会更新状态,它不会慢它只是根本不更新。我想知道这是否是因为我将它传递给了事件监听器?
事件监听器和useState初始化
function SideNav(props: any) {
const [scrollSection, setScrollSection] = React.useState(0);
React.useEffect(() => {
window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection));
return () => {
window.removeEventListener('scroll', () => checkSection(scrollSection, setScrollSection));
};
}, []);
传递给事件侦听器的函数
function checkSection(scrollSection: number, setScrollSection: Function){
let scrollSections = [0, 1538, 2583, 2089, 3089]
const scrollY = window.scrollY;
setScrollSection(1);
console.log("scroll Y: "+scrollY);
console.log("section: "+scrollSection)
}
【问题讨论】:
-
两个问题: 1. 这不是删除事件侦听器的方式。你必须使用相同的功能,而不是等效函数,在对
removeEventListener的调用中。 2. 您的事件侦听器关闭第一的scrollSection的版本,不是稍后调用您的组件函数时看到的更新版本。 -
当你尝试实现这个时,你会遇到任何错误吗?
标签: javascript reactjs