【问题标题】:How to prevent right mouse button click onMouseDown() react js?如何防止鼠标右键单击onMouseDown()反应js?
【发布时间】:2021-08-01 01:35:36
【问题描述】:

我正在使用onMouseDownonMouseUp 进行更好的控制。 我已经有onContextMenu,但是我如何防止右键单击onMouseDownonMouseUp。我只想单击左键。

因为目前有 2 个事件同时触发。我的上下文菜单和其他功能同时打开。

【问题讨论】:

标签: reactjs


【解决方案1】:

您可以检查是否e.button === 2。 当您右键单击时,e.button 的值是2

虽然我不确定它是否支持浏览器。

您可以查看此示例。

const {useState} = React;

const App = () => {
  const [value, setValue] = useState('left or right click');

  const handleMouseDown = (e) => {
    if(e.button === 2) return;
    console.log('handleMouseDown');
  }
  
  const handleMouseUp = (e) => {
    if(e.button === 2) return;
    console.log('handleMouseUp');
  }
  
  const handleContextMenu = (e) => {
    console.log('handleContextMenu');
  }

  return (
    <div className="test" onMouseDown={handleMouseDown} onMouseUp={handleMouseUp} onContextMenu={handleContextMenu} >{value}</div>
  );
};

// Render it
ReactDOM.render(
  <App/>,
  document.getElementById("react")
);
.test {
  width: 100vw;
  height: 100vh;
  text-align: center;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

【讨论】:

    【解决方案2】:
    onMouseDown={(event) => {
     if (event.button === 0) { ***write some code***}
    }}
    

    event.button === 0 left, event.button === 1 middle, event.button === 2 right,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      相关资源
      最近更新 更多