[英]How to prevent right mouse button click onMouseDown() react js?
I am using onMouseDown
and onMouseUp
for better control.我正在使用
onMouseDown
和onMouseUp
进行更好的控制。 I already have onContextMenu
but how I can prevent the right button click on onMouseDown
and onMouseUp
.I only want the left button to be clicked.我已经有
onContextMenu
但是如何防止右键单击onMouseDown
和onMouseUp
。我只希望单击左键。
because currently 2 events triggering at the same time.因为目前有 2 个事件同时触发。 My context menu and other function open at the same time.
我的上下文菜单和其他 function 同时打开。
You can check if e.button === 2
or not.您可以检查
e.button === 2
与否。 When you right click then the value of e.button
is 2
.当您右键单击时,
e.button
的值为2
。
Though i'm not sure about it's browser support.虽然我不确定它是否支持浏览器。
You can check this example.你可以检查这个例子。
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>
onMouseDown={(event) => {
if (event.button === 0) { ***write some code***}
}}
event.button === 0 left
, event.button === 1 middle
, event.button === 2 right
, event.button === 0
left
, event.button === 1 middle
, event.button === 2 right
,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.