【问题标题】:Removing event listener in React (lodash.throttle)在 React (lodash.throttle) 中移除事件监听器
【发布时间】:2018-04-10 16:18:01
【问题描述】:

removeEventListener() 在我不使用来自 lodash 的 throttle() 时有效。

   window.addEventListener('scroll', this.checkVisible, 1000, false);
     window.removeEventListener('scroll', this.checkVisible, 1000, false);

(我在构造函数中绑定了方法)


不幸的是,使用 throttle(this.checkVisible) 函数包裹它 - 不起作用。我认为这是因为在尝试删除侦听器时,throttle() 创建了新实例,也许我应该全局绑定它。但是如何(如果是这样的话)?

  import React from 'react';
    import throttle from 'lodash.throttle';
    
    class About extends React.Component {
      constructor(props) {
        super(props);
    
        this.checkVisible = this.checkVisible.bind(this);
      }
    
      componentDidMount() {
        window.addEventListener('scroll', throttle(this.checkVisible, 1000), false);
    
      }
    
      checkVisible() {
       if (window.scrollY > 450) {
        // do something
        window.removeEventListener('scroll', throttle(this.checkVisible, 1000),
        false);
        }
      }
    
      render() {
        return (
          <section id="about"> something
          </section>
        );
      }
    }
    
    export default About;

【问题讨论】:

    标签: javascript reactjs events dom-events


    【解决方案1】:

    Lodash trottle 创建了一个受限制的函数,因此您需要存储对它的引用才能删除事件监听器。

    import React from 'react';
    import throttle from 'lodash.throttle';
    
    class About extends React.Component {
      constructor(props) {
        super(props);
    
        this.checkVisible = this.checkVisible.bind(this);
        // Store a reference to the throttled function
        this.trottledFunction = throttle(this.checkVisible, 1000);
      }
    
      componentDidMount() {
        // Use reference to function created by lodash throttle
        window.addEventListener('scroll', this.trottledFunction, false);
    
      }
    
      checkVisible() {
       if (window.scrollY > 450) {
        // do something
        window.removeEventListener('scroll', this.trottledFunction, false);
        }
      }
    
      render() {
        return (
          <section id="about"> something
          </section>
        );
      }
    }
    
    export default About;
    

    【讨论】:

    • 感谢您的回答!我整天都被这样的问题困扰。
    • 这让我很困扰,我还写了一篇关于它的博客文章 - chipcullen.com/… - 再次感谢你,@lagerone
    • 嗨,你能告诉这将如何与功能组件一起工作
    • @Harsimer 你将不得不使用钩子来实现这个功能组件。类似stackoverflow.com/a/62017005/975720
    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 2011-12-30
    • 1970-01-01
    • 2012-02-09
    • 2021-08-23
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多