最好的方法是创建一个绑定函数,以便以后可以引用它以在卸载时删除侦听器,如下所示:
class Foo extends Component {
constructor(props) {
super(props);
this.handleScrollChange = this.handleScrollChange.bind(this);
}
handleScrollChange() {
const isPassedTop = window.pageYOffset > 100;
if (isPassedTop !== this.state.isPassedTop) {
this.setState({ isPassedTop: isPassedTop })
}
}
componentDidMount() {
document.addEventListener('scroll', this.handleScrollChange, true);
}
componentWillUnmount() {
document.removeEventListener('scroll', this.handleScrollChange);
}
}