Javascript React 合成事件区分左击和右击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31110184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Synthetic Event distinguish Left and Right click events
提问by Bhargav Ponnapalli
I am trying to distinguish between left and right clicks in an OnClick function. But,
我试图区分 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>
}
});
Turns out e.which is undefined for Synthetic Events. How can I distinguish between left and right clicks here?
结果是 e.which 对于Synthetic Events是 undefined 。这里如何区分左右点击?
回答by Dhiraj
You can do something like this too. Have both onClick and onContextMenu handlers
你也可以做这样的事情。有 onClick 和 onContextMenu 处理程序
return <p onClick={this.handleClick} onContextMenu={this.handleClick}>Something </p>
You can either check for nativeEventas the other answer suggests or check for type. (Also, prevent default if it is a right click.)
您可以nativeEvent按照其他答案的建议进行检查,也可以检查type. (另外,如果是右键单击,请防止默认。)
Using type
使用 type
handleClick: function(e) {
if (e.type === 'click') {
console.log('Left click');
} else if (e.type === 'contextmenu') {
console.log('Right click');
}
}
Using nativeEvent
使用 nativeEvent
handleClick: function(e) {
if (e.nativeEvent.which === 1) {
console.log('Left click');
} else if (e.nativeEvent.which === 3) {
console.log('Right click');
}
}
Here is a demo http://jsbin.com/seyeliv/edit?html,output
回答by Brigand
The property you're looking for is e.buttonor e.buttons.
您正在寻找的属性是e.button或e.buttons。
The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2.
– MDN:Web/Events/click
鼠标事件触发时按下的按钮编号:左键=0,中键=1(如果存在),右键=2。
– MDN:Web/事件/点击
However, with or without react, I'm only getting click events with the left mouse button (trackpad). You could use onMouseDown which works for me.
但是,无论是否有反应,我只能使用鼠标左键(触控板)获得点击事件。您可以使用对我有用的 onMouseDown。
Here's a demousing e.buttons. You may want to preventDefault in onContextMenu also.
这里有一个演示使用e.buttons。您可能还想在 onContextMenu 中防止默认。
回答by marcel
Use:
用:
if (e.button === 0) { // or e.nativeEvent.which === 1
// do something on left click
}

