繁体   English   中英

从可拖动组件中删除事件侦听器

[英]Remove an event listener from a draggable component

我正在使用React中的ES6组件并制作一个简单的滑块组件。 在我的mousedown事件中,我正在为mousemove添加一个监听器,因为onDrag的处理程序不够响应。 我试图在mouseup上删除mousemove监听器,因为这意味着用户完成了拖动滑块。 但是,我无法关闭我的事件监听器,并且它一直触发onDrag函数(将记录“我仍然执行”)。 我错过了一些明显的东西吗 我尝试传递一个命名函数,就像其他建议的答案一样,但它仍然会触发。

ES6代码:

import React from 'react';

class PriceSlider extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {positionX: 0, offset: null, dragging: null}
  }
  _onDrag(e) {
    console.log("i still execute")
    if(e.clientX > 0) {
      this.setState({positionX: e.clientX});
    }
  }
  _removeDragHandlers() {
    let node = React.findDOMNode(this.refs.circle1);
    node.removeEventListener("mousemove", this._onDrag.bind(this), false);
    return;
  }
  _addDragHandlers() {
    let node = React.findDOMNode(this.refs.circle1);
    node.addEventListener("mousemove", this._onDrag.bind(this), false);
    return;
  }
  componentDidMount() {
    this.setState({offset: this.refs.circle1.getDOMNode().getBoundingClientRect().left })
  }
  _onMouseDown(e) {
    this._addDragHandlers();
  }
  _onMouseUp(e){
    this._removeDragHandlers();
  }
  render() {
    let circle1Style = {left: this.state.positionX - this.state.offset}

    if(this.state.positionX === 0) {
      circle1Style = {left: this.state.positionX}
    }

    return(
      <div className="slider">
        <span className="value">Low</span>
        <span className="circle" style={circle1Style} onMouseDown={this._onMouseDown.bind(this)} onMouseUp={this._onMouseUp.bind(this)} ref="circle1"></span>
        <span className="line"></span>
        <span className="circle" ref="circle2"></span>
        <span className="value">High</span>
      </div>
    )
  }
}

使用命名函数,我尝试做类似的事情:

node.addEventListener("mousemove", function onDrag() {
  if(!this.state.dragging)  {
    node.removeEventListener("mousemove", onDrag, false)
  }
})

无济于事。 任何有关改进这方面的帮助或建议都非常感谢。 我没有包含jQuery或其他Javascript库,需要在没有插件或库的帮助下解决这个问题。

this._onDrag.bind(this)每次都返回一个新函数 - 所以你添加然后尝试删除不同的函数。 您需要执行一次,然后每次都引用相同的函数:

constructor(props, context) {
    …
    this._onDrag = this._onDrag.bind(this);
}
_removeDragHandlers() {
    …
    node.removeEventListener("mousemove", this._onDrag);
}
_addDragHandlers() {
    …
    node.addEventListener("mousemove", this._onDrag, false);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM