React Synthetic Event区分左右点击事件

Bha*_*lli 33 javascript javascript-events reactjs

我试图区分OnClick函数中的左键和右键单击.但,

var r = React.createClass({
   handleClick : function(e){
       //left click
       if(e.which==1){ 
          //Do something
       }
   },
   render : function(){
       return <p onClick={this.handleClick}>Something </p>
   }
});
Run Code Online (Sandbox Code Playgroud)

结果是合成事件未定义的e.which.如何区分左右点击?

Dhi*_*raj 48

你也可以这样做.同时拥有onClick和onContextMenu处理程序

return <p onClick={this.handleClick} onContextMenu={this.handleClick}>Something </p>
Run Code Online (Sandbox Code Playgroud)

你可以检查nativeEvent其他答案建议或检查type.(另外,如果是右键单击,请防止默认.)

运用 type

handleClick: function(e) {
  if (e.type === 'click') {
    console.log('Left click');
  } else if (e.type === 'contextmenu') {
    console.log('Right click');
  }
}
Run Code Online (Sandbox Code Playgroud)

运用 nativeEvent

handleClick: function(e) {
  if (e.nativeEvent.which === 1) {
    console.log('Left click');
  } else if (e.nativeEvent.which === 3) {
    console.log('Right click');
  }
}
Run Code Online (Sandbox Code Playgroud)

这是演示http://jsbin.com/seyeliv/edit?html,output

  • 对于左键和中键滚动单击,e.type 的值为“单击”。=\(已投票,疯狂寻找这个答案) (2认同)

Bri*_*and 16

您要找的房产是e.buttone.buttons.

触发鼠标事件时按下的按钮编号:左按钮= 0,中按钮= 1(如果存在),右按钮= 2.
- MDN:网络/活动/点击

但是,无论有没有反应,我只能用鼠标左键(触控板)获得点击事件.你可以使用对我有用的onMouseDown.

这是一个使用的演示e.buttons.您可能还希望在onContextMenu中使用preventDefault.


mar*_*cel 7

使用:

if (e.button === 0) { // or e.nativeEvent.which === 1
    // do something on left click
}
Run Code Online (Sandbox Code Playgroud)

这是一个演示


Kri*_*nov 5

onContextMenu={e => console.log("right-click")}


onClick={e => console.log("left-click")}
Run Code Online (Sandbox Code Playgroud)

我在React 官方文档的“鼠标事件”部分找到了这个解决方案。

以下是onContextMenu 合成事件的TypeScript 定义。