[英]Javascript event not registering for right click event (in React)
我正在 React 中的一個項目中工作,我需要區分左右單擊以及鼠標左鍵和右鍵。 我對鼠標按下事件完全沒有問題,但在單擊事件時遇到了大問題。
在我的 onMouseDown 處理程序中,我正在檢查 event.button 以查看鼠標左側或右側發生鼠標按下的天氣(event.button === 0 表示鼠標左鍵按下,event.button === 2 用於鼠標右鍵)。 這按預期完美運行。
但是,完全相同的邏輯不適用於我的 onClick 處理程序上的單擊事件; 只有左鍵單擊有效。 實際上,當我嘗試在單擊時記錄整個事件 object 時,右鍵單擊根本沒有響應。 好像單擊事件不適用於右鍵單擊。
對於上下文,我已經關閉了我正在談論的元素上的上下文菜單,因為這會妨礙我,但是即使我正常允許上下文菜單,我也沒有運氣右鍵單擊事件。
這里有一些代碼可以告訴你我在說什么:
// Works perfectly
const handleMousedown = (e) => {
if (e.button === 0) {
setLeftMousedown(true);
// console.log(e.button);
}
if (e.button === 2) {
setRightMousedown(true);
// console.log(e.button);
}
};
*******************************
// Does NOT work for the right click, and the console.log at the top only fires at all on left clicks
const handleClick = (e, i, j) => {
console.log(e); // only registers for left click
if (e.button === 0) {
let gridCopy = JSON.parse(JSON.stringify(grid));
gridCopy[i][j].on = !gridCopy[i][j].on;
setGrid(gridCopy);
}
if (e.button === 2) {
console.log('rightclick');
let gridCopy = JSON.parse(JSON.stringify(grid));
gridCopy[i][j].wall = !gridCopy[i][j].wall;
setGrid(gridCopy);
}
};
有什么想法為什么會發生這種情況,或者我如何將右鍵單擊事件與左鍵單擊事件分開注冊?
單擊事件不適用於鼠標右鍵。 您應該使用 mouseDown 或使用onContextMenu
: https://stackoverflow.com/a/28656242/4949918
對於右鍵單擊,您需要設置onContextMenu
onContextMenu={this.handleClick}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.