有什么方法可以检测 React JS 中的中间点击吗?

Is there any way to detect middle click in React JS?

我正在尝试找到一种方法来检测 React JS 中的中间点击事件,但到目前为止还没有成功。

在 Chrome React 的合成点击事件中确实显示了被点击的按钮 ->

mouseClickEvent.button === 0 // Left

mouseClickEvent.button === 1 // Middle but it does not execute the code at all

mouseClickEvent.button === 2 // Right (There is also onContextMenu with event.preventDefault() )

请分享您的观点。

您可以添加一个 mouseDown 事件,然后检测中间按钮点击,例如:

handleMouseDown = (event) => {
   if(event.button === 1) {
      // do something on middle mouse button click
   }
}

您的代码可能如下所示:

class App extends React.Component {
   constructor() {
     super();

     this.onMouseDown = this.onMouseDown.bind(this);
   }
   componentDidMount() {
       document.addEventListener('mousedown', this.onMouseDown);
   }
   componentWillUnmount() {
       document.removeEventListener('mousedown', this.onMouseDown);
   }
   onMouseDown(event) {
       if (event.button === 1) {
          // do something on middle mouse button click
       }
   }
   render() {
     // ...
   }
}

您可以在此处找到有关 MouseEvent.button 的更多信息: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

小心。使用 mousedown 并不总是能让你得到你想要的行为。 "click" 既是 mousedown 又是 mouseup,其中 xy 值没有改变。理想情况下,您的解决方案会将 xy 值存储在 mousedown 上,当 mouseup 出现时,您将进行测量以确保它们位于同一位置。

甚至比 mousedown 更好的是 pointerdown。这配置了与 "touch" 和 "pen" 事件以及 "mouse" 事件的兼容性。如果指针事件与您应用的兼容浏览器兼容,我强烈推荐此方法。

您可以使用 React Synthetic 事件,如下所述

<div tabIndex={1} onMouseDown={event => { console.log(event)}}>
    Click me
</div>

如果您使用的是无状态组件:

JS

const mouseDownHandler = ( event ) => {
  if( event.button === 1 ) {
    // do something on middle mouse button click
  }
}

JSX

<div onMouseDown={mouseDownHandler}>Click me</div>

希望对您有所帮助。

你可以保留onClick。在 React 中,您可以访问 nativeEvent 属性 从那里您可以读取哪个按钮被按下:

const clickHandler = (evt) => {
  if (e.nativeEvent.button === 1) {
    ...
  }
}

return (
  <a onClick={clickHandler}>test</a>
)

现代的做法是通过 onAuxClick 事件:

import Card from 'react-bootstrap/Card';
import React, { Component } from 'react';

export class MyComponent extends Component {

  onAuxClick(event) {
    if (event.button === 1) {
      // Middle mouse button has been clicked! Do what you will with it...
    }
  }
    
  render() {
    return (
      <Card onAuxClick={this.onAuxClick.bind(this)}>
      </Card>
    );
}