javascript - 移除事件后触发的滚动事件监听器
问题描述
我在使用 React 构建的组件中的窗口对象上使用滚动事件。componentDidMount()
我在生命周期方法中添加了监听器。
componentDidMount() {
window.addEventListener('scroll',this.handleScrollChange);
}
现在我有一个按钮,它滚动到它的点击事件的某个位置。
当我单击按钮时,会触发以下功能:
window.removeEventListener('scroll', this.handleScrollChange);
this.changePageUrl(currentData);
// Add it back again.
this.setState(
{
currentData
},
() => {
window.scrollTo({
top: currentTop + 100,
behavior: 'smooth',
});
setTimeout(() => {
window.addEventListener('scroll', this.handleScrollChange);
}, 10000);
},
);
即使我将 setTimeout 增加到10000
,我的滚动事件更改处理函数也会this.handleScrollChange
被触发,并且滚动事件不会被删除。
阅读其他一些问题,我已经在构造函数中绑定了我的函数,所以函数的引用不是问题:
constructor(props) {
super(props)
this.handleScrollChange = this.handleScrollChange.bind(this);
}
可以在示例中看到复制的代码: https ://stackblitz.com/edit/react-djblfj?file=index.js
click
如何在按钮单击时删除事件侦听器并在滚动完成后再次添加它?
解决方案
推荐阅读
- c - printf("%d",*p++); 的意外结果;
- javascript - for 循环:javaScript 中的嵌套数组
- azure-digital-twins - ADT RestAPI 的 POST 命令返回“HTTP/1.1 405 Method Not Allowed Allow: DELETE,GET,PATCH,PUT Content-Length:0”
- excel-formula - Excel 中的国际函数名称
- excel - 将 Sharepoint Excel (xlsx) 文件数据导出为 XML 文件
- visual-studio - 为什么我的 Visual Studio 2019 项目没有运行?
- swift - 如何Vstack工作表视图按钮
- javascript - 为什么 getServerSideProps 可以在 index.js 上工作,但不能在 [id].js 上使用 NextJS
- javascript - 当 bio 包含“@”时,Twitter API update_profile 返回 401
- python - “PerformanceWarning:DataFrame高度碎片化。这通常是多次调用`frame.insert`的结果,性能很差。”