处理React onDoubleClick并单击onClick以获取相同的元素

时间:2018-03-09 05:52:17

标签: reactjs onclick ondoubleclick

当我将单个onClick事件添加到元素以及将onDoubleClick事件添加到同一元素时,单击也会在双击时触发。我想把它分开,所以只有一个事件被解雇为单人或双人。我在Jquery中找到了一些例子,但是我想要一个React的干净函数。

 handleClick = () => {
   console.log('only fire click')
 }

 handleDoubleClick = () => {
   console.log('only fire double click')
 }

 render () {
  return <Element 
             onClick={evt => this.handleClick}
             onDoubleClick={evt => this.handleDoubleClick} 
         ></Element>
 }

2 个答案:

答案 0 :(得分:5)

基于我为jquery找到的其他片段,我创建了这个简单的函数,根据点击产生正确的事件。希望这有助于其他React。

componentWillMount = props => {
  this.clickTimeout = null
}

handleClicks = () => {
  if (this.clickTimeout !== null) {
    console.log('double click executes')
    clearTimeout(this.clickTimeout)
    this.clickTimeout = null
  } else {
    console.log('single click')  
    this.clickTimeout = setTimeout(()=>{
    console.log('first click executes ')
    clearTimeout(this.clickTimeout)
      this.clickTimeout = null
    }, 2000)
  }
}

render () {
  return <Element 
             onClick={evt => this.handleClicks}
         ></Element>
}

答案 1 :(得分:1)

我希望下面的代码可以帮助您点击单击和双击,

constructor(props){
  super(props);
  this.clickCount = 0;
  this.singleClickTimer = '';
}

singleClick = () => {
    console.log('only fire click')
}

handleDoubleClick = () => {
    console.log('only fire double click')
}
handleClicks(){
    this.clickCount++;
  if (this.clickCount === 1) {
    this.singleClickTimer = setTimeout(function() {
      this.clickCount = 0;
      this.singleClick();
    }.bind(this), 300);

  } else if (this.clickCount === 2) {
    clearTimeout(this.singleClickTimer);
    this.clickCount = 0;
    this.handleDoubleClick();
  }
}
render () {
  return <Element 
             onClick={() => this.handleClicks()} 
         ></Element>
 }

供您参考,https://jsfiddle.net/69z2wepo/130223/