javascript - document.removeEventListner 未删除 ReactJS 中的事件

标签 javascript reactjs dom-events mouseevent

u我有React组件,我使用componentDidMount生命周期钩子(Hook)将mousedown事件绑定(bind)到文档。当鼠标按下事件触发时,我将另外两个事件 mousemovemouseup 绑定(bind)到 document ,我还删除了 mouseup 处的这些事件事件。

我的问题是,当 mouseup 事件触发时,它应该删除 mousemovemouseup 但它不起作用。相反,每次我点击页面 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/

相关文章:

javascript - 鹅毛笔 : How to add links to the editor content that don't get saved to the delta?

reactjs - 如何在使用 React hooks 挂载组件后触发事件

android - 应用在元数据中包含对 Android 的引用

javascript - 使用 "JavaScript: The Definite Guide"中的 onLoad 函数有什么意义?

javascript - UI5 - 过滤器组合框放置问题

javascript - mustache 式双括号的正则表达式?

javascript - React Native WebView onNavigationStateChange 不是一个函数(运行 jest 测试时)

javascript - js错误: You may need an appropriate loader

javascript - 如何使用 Javascript 将事件添加到 html 标签

javascript - HTML 5 拖动事件