Disable ContextMenu in ReactJS

混江龙づ霸主 提交于 2021-02-18 10:34:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!