首页 > 解决方案 > 移除事件后触发的滚动事件监听器

问题描述

我在使用 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如何在按钮单击时删除事件侦听器并在滚动完成后再次添加它?

标签: javascripthtmlreactjsdom

解决方案


推荐阅读