简体   繁体   中英

Javascript event not registering for right click event (in React)

I'm working on a project in React where I need to differentiate between right and left clicks, as well as left and right mouse-downs. I am having no problems at all with the mouse-down event, but am having a big problem with the click event.

In my onMouseDown handler, I'm checking event.button to see weather the mouse-down occurred with the left or right side of the mouse (event.button === 0 for left mouse-down, and event.button === 2 for right mouse-down). This is working perfectly as expected.

However, the exact same logic is not working for the click event on my onClick handler; only the left click is working. In fact, when I try to log the entire event object on click, there is no response at all with the right click. It's as if the click event doesn't work for right clicks.

For context, I have turned off the context menu on the element I'm talking about because that was getting in the way, but even when I allow the context menu as normal I am having no luck with the right click event.

Here is some code to show you what I'm talking about:

// 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);
    }
  };

Any ideas why this is happening OR how I can register right click events separate from left click events?

Click events don't work with right mouse button. You should ever use mouseDown or use onContextMenu : https://stackoverflow.com/a/28656242/4949918

For right click, you need to set the onContextMenu prop

onContextMenu={this.handleClick}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM