I am using onMouseDown
and onMouseUp
for better control. 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.
because currently 2 events triggering at the same time. My context menu and other function open at the same time.
You can check if e.button === 2
or not. When you right click then the value of e.button
is 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
,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.