2

在最近一次react.js项目中,需要做监听滚动事件,一开始搜索了下别人的做法,按照步骤却发现window.addEventListener监听无效。
在constructor中绑定 this

constructor () {
    super()
    this.handleScroll = this.handleScroll.bind(this)
}
// 组件加载时
componentDidMount () {
    window.addEventListener('scroll', this.handleScroll)
}
// 组件卸载时
componentWillUnmount () {
    window.removeEventListener("scroll", this.handleScroll)
}
// 监听滚动
handleScroll () {
    console.log('进来')
}

一开始没绑定this不行,后面constructor中绑定 this加上发现还是无效。然后查找了addEventListener() 方法的用法时发现:有三个参数_element_.addEventListener(_event_,_function_,_useCapture_)

1586416197(1).jpg

useCapture设置为true时候就发现解决了这个问题
下面贴出我的解决方法:去掉constructor的绑定this,直接用箭头函数

// 组件加载时
componentDidMount () {
    window.addEventListener('scroll', this.handleScroll, true)
}
// 组件卸载时
componentWillUnmount () {
    window.removeEventListener('scroll', this.handleScroll, true)
}
// 监听滚动
handleScroll = () => {
    console.log('进来')
}

Sunny
6 声望0 粉丝