同时激活onClick和onTouchStart

Yur*_*uri 7 javascript reactjs

我的React应用程序中有一个div,我需要处理点击和触摸.但是,当我点击手机时,它会触发两个事件.

如果我在手机上滑动或者如果我点击普通浏览器,它工作正常,每种情况下只触发一个事件.

如何解决这个问题?

<div
  className={myClasses}
  onClick={this.myHandle}
  onTouchStart={this.myHandle}
  >&nbsp;
</div>
Run Code Online (Sandbox Code Playgroud)

Rob*_*uch 9

事件被触发的时间有一个定义的顺序():

touchstart
Zero or more touchmove events, depending on movement of the finger(s)
touchend
mousemove
mousedown
mouseup
click
Run Code Online (Sandbox Code Playgroud)

预防事件

如果您想clicktouchend之前触发事件的情况下阻止事件,您可以event.preventDefault()touchend事件处理程序中使用以阻止click事件触发。

  • 在 React 中,我必须执行“event.stopPropagation()”来阻止它同时触发“onTouchStart”和“onMouseDown” (2认同)

Yur*_*uri 8

使用触摸和鼠标之间的类似事件解决了这个问题.touchStart/mouseDown或touchEnd/mouseUp.根据每种情况,它会发射一个或另一个.

<div
  className={myClasses}
  onMouseUp={this.myHandle}
  onTouchEnd={this.myHandle}
  >&nbsp;
</div>
Run Code Online (Sandbox Code Playgroud)