【发布时间】: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