我正在使用React中的ES6组件并制作一个简单的滑块组件。在我的mousedown事件中,我正在为mousemove
添加一个监听器,因为onDrag
的处理程序不够响应。我正在尝试删除mousemove
上的mouseup
侦听器,因为这意味着用户已完成拖动滑块。但是,我无法关闭我的事件监听器,并且它会一直触发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库,需要在没有插件或库的帮助下解决这个问题。
答案 0 :(得分:1)
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);
}