React Synthetic Event 区分左击和右击事件

React Synthetic Event distinguish Left and Right click events

我试图区分 onClick 函数中的左键单击和右键单击:

const App = () => {
  const handleClick = (e) => {
    // detect a left click
    if (e.which == 1){ 
      // do something
    }
  };
  return <p onClick={handleClick}>Something</p>;
};

原来 e.which 未定义 Synthetic Events。这里如何区分左键和右键?

使用:

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

Here is a DEMO

在现代版本的 React (v16+) 中,需要传递 onClickonContextMenu 属性来检测左键和右键单击事件:

return <p onClick={handleClick} onContextMenu={handleClick}>Something</p>

您可以检查 e.nativeEvent.button(正如其他答案所暗示的),或者检查 e.type 合成事件本身。

使用e.type

const handleClick = (e) => {
  if (e.type === 'click') {
    console.log('Left click');
  } else if (e.type === 'contextmenu') {
    console.log('Right click');
  }
};

使用e.nativeEvent

const handleClick = (e) => {
  if (e.nativeEvent.button === 0) {
    console.log('Left click');
  } else if (e.nativeEvent.button === 2) {
    console.log('Right click');
  }
};

这是一个 updated demo 演示它是如何工作的。

您可能还想阅读 React documentation for SyntheticEvent

(original demo)

您要查找的属性是e.buttone.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

但是,无论是否有反应,我都只能通过鼠标左键(触控板)获得点击事件。您可以使用对我有用的 onMouseDown。

这里是 demo 使用 e.buttons。您可能还想在 onContextMenu 中防止默认。

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


onClick={e => console.log("left-click")}

我在 React's official documentation 的“鼠标事件”部分找到了这个解决方案。

这里是onContextMenu的合成事件TypeScript definition