问题
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:
回答1:
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
来源:https://stackoverflow.com/questions/53810524/disable-contextmenu-in-reactjs