u我有React组件,我使用componentDidMount
生命周期钩子(Hook)将mousedown
事件绑定(bind)到文档。当鼠标按下事件触发时,我将另外两个事件 mousemove
和 mouseup
绑定(bind)到 document ,我还删除了 mouseup
处的这些事件事件。
我的问题是,当 mouseup
事件触发时,它应该删除 mousemove
和 mouseup
但它不起作用。相反,每次我点击页面 mouseup
都会触发多次,例如:1、3、6、10、15...它会成倍增加。
当componentWillUnmount
时也没有从文档中删除事件。
import React, { Component } from 'react'
class SandBox extends Component{
componentDidMount(){
document.addEventListener('mousedown', this.mouseDown.bind(this))
}
//mouseDown
mouseDown(){
document.addEventListener('mouseup', this.mouseUp.bind(this))
document.addEventListener('mousemove', this.mouseMove.bind(this))
}
//mouseUp
mouseUp(){
// this is not removing the events from document
document.removeEventListener('mouseup', this.mouseUp, false)
document.removeEventListener('mousemove', this.mouseMove, false)
// this triggers 1,3,6,10,15 times
console.log('mose up')
}
moseMove(){
// mosemoveCodes
}
}
最佳答案
当您在函数上绑定(bind)
时,它将创建新函数,并且您无法引用旧的this。无论如何,这就是为什么removeEventlistener
找不到您的函数。您可以使用 es6 class
constructor
来修复此问题。
class YourComponent extends Component {
constructor(props){
super(props)
//bind and reference your methods here
this.mouseDown = this.mouseDown.bind(this)
this.mouseUp = this.mouseUp.bind(this)
this.mouseMove = this.mouseMove.bind(this)
// now its pointing corectcly
}
// lifecycle
componentDidMount(){
document.addEventListener('mousedown', this.mouseDown.bind(this))
}
//mouseDown
mouseDown(){
document.addEventListener('mouseup', this.mouseUp)
document.addEventListener('mousemove', this.mouseMove)
}
//mouseUp
mouseUp(){
// this is will work
document.removeEventListener('mouseup', this.mouseUp, false)
document.removeEventListener('mousemove', this.mouseMove, false)
console.log('mouse up')
}
// unmount
componentWillUnmount(){
// this is will work
document.removeEventListener('mousedown', this.mouseDown, false)
}
}
关于javascript - document.removeEventListner 未删除 ReactJS 中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44361293/