如何停止双击事件的传播

时间:2017-03-29 15:02:03

标签: javascript reactjs events javascript-events event-handling

考虑这个组成部分:

<Card onClick={openWindowHandler}>
  <Editable onDoubleClick={enableInputHandler} />
</Card>

我想要实现的是在调度onDoubleClick事件时停止事件传播,,因此&#39; openWindowHandler&#39;函数未被调用。但是,onClick将在onDoubleClick之前触发!

我可以通过应用_.debounce函数来区分调用哪个事件类型,但到那时,事件已经被调度,因此无法调用stopPropagation()。

class App extends React.Component {
  delayedCallback = _.debounce(function (event) {
    if (event.type === 'dblclick') {
      // too late to call event.stopPropagation()
    } else {
      // continue
    }
  }, 250)

  handleClick = (event) => {
    event.persist()
    this.delayedCallback(event)
  }

  render () {
    return (
      <Card onClick={this.handleClick}>
        <Editable onDoubleClick={this.handleClick} />
      </Card>
    )
  }
}

有什么办法吗?

修改 单击<Editable />元素应该冒泡到父母,导致&#39; openWindowHandler&#39;调用

2 个答案:

答案 0 :(得分:0)

示例:

// This will return a event
function clickHandlerModule() {
    var clickCount = 0;
    var timer = null;
    var delay = 250;
    return function(event) {
        clickCount++;
        if(clickCount === 1){
            timer = setTimeout(function(){
                console.log('SINGLE CLICK');
                clickCount = 0;
            }, delay);
        } else {
            clearTimeout(timer);
            console.log('DOUBLE CLICK');
            clickCount = 0;
        }
    }
}


class App extends React.Component {
  constructor() {
    super();
    this.clickHandler = clickHandlerModule()
  }
  render () {
    return (
      <Card onClick={this.clickHandler}>
        <Editable />
      </Card>
    )
  }
}

答案 1 :(得分:0)

export class Sample {
   clickCount = 0;

   onItemClick() {
        let isDoubleClick = false;
        this.clickCount++;
        if (this.clickCount === 1) {
            setTimeout(() => {
               if (this.clickCount > 1) {
                isDoubleClick = true;
                console.log('dblclick');
               }
               this.clickCount = 0;
               if (!isDoubleClick) {
                console.log('click');
               }
           }, 250);
        }
    }
  } 
}

HTML

  <Card (click)="onItemClick()">
    <Editable (dblclick)="SomeMethodForDblClick()" />
  </Card>

因此,您可以在 cart.component 中为 click && dblClick 事件编写一些方法,并使用 dblclick 用于 editable.component ,没有冲突

P.S。是的,我使用的是棱角形,对不起语法:)