【发布时间】:2015-09-17 20:59:18
【问题描述】:
我正在使用 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 库,需要在没有插件或库的帮助下解决这个问题。
【问题讨论】:
标签: javascript javascript-events event-handling reactjs