为同一元素处理 React onDoubleClick 和单个 onClick

Handle React onDoubleClick and single onClick for same element

当我向一个元素添加一个 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>
 }

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

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>
}

我希望下面的代码能帮助您触发单击和双击,

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/