gpt4 book ai didi

javascript - 在 React 中移除事件监听器 (lodash.throttle)

转载 作者:可可西里 更新时间:2023-11-01 02:37:30 24 4
gpt4 key购买 nike

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

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

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


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

  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;

最佳答案

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;

关于javascript - 在 React 中移除事件监听器 (lodash.throttle),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com