简体   繁体   中英

Disable ContextMenu in ReactJS

first post here so hopefully I can ask this question the most helpful manner possible. I'm pretty new to coding and in trying to push myself decided to attempt to recreate Minesweeper using React and not using any tutorial. I've gotten a lot of the functionality but am really stuck on this part. I am using the event listener 'onContextMenu' to register a right click to "flag" a mine in the program. But I can't figure the right way to isolate it or maybe it's a syntax issue preventing the menu from popping up at the same time. In JS it seems really simple of just returning false on the event listener, but I can't figure it out in React.

I'm currently using 'onContextMenu' to handle my right click and calling a function that handles the flag assignment with that event listener. Can I also within a function disable the contextMenu from showing?

Thank you for any help you can offer!

The div being rendered looks like this right now:

<div
   contextMenu="none"
   className="square"
   onContextMenu={() => this.props.rightClick(props.arrayVal)}
   onClick={() => {this.props.playerTurn(this.props.index)}}
   style={{color:COLORS[this.props.arrayVal], backgroundImage:this.backgroundChooser(this.props.arrayVal)}}
    >
       {this.squareContent(this.props.arrayVal)}
</div> 

The function being called looks like this:

rightClick = (id) => {
    let { board, gameWon, minesLeft } = this.state
    let mineCount = minesLeft
    let move = board
    if (gameWon === false) {
        if (board[id] === -1) {
            move[id] = 9
            mineCount -= 1
        } else if (board[id] === 9) {
            move[id] = "?"
            mineCount += 1
        } else if (board[id] === "?") {
            move[id] = -1
        }
        this.setState({
            board: move,
            minesLeft: mineCount
        })
    }
}

I was able to waste another long bit of time and get a senior dev friend to look at this for me. Here was the solution. Hope it helps someone else :-)! See comment below:

I know its an old one but heres my solution for this: first, select the element you want to disable the contextMenu for (in this occasion its a div element) and just add this piece to the element:

<div onContextMenu={(e)=> e.preventDefault()}... />

right clicking the div above won't trigger the context menu

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