在 React 中禁用 Firefox 的右键单击上下文菜单

Disable Firefox's right click context menu in React

我正在尝试禁用右键单击特定 div 时弹出的上下文菜单。在我做的渲染中

<div onContextMenu={(e) => {
    console.log(e); 
    e.preventDefault(); 
    e.stopPropagation(); 
    return false
}}>

它确实打印了,所以我知道它是附件,但它仍然在 firefox ESR 60.8.0 中弹出,即使它在 chrome 中被阻止。

原因:我有一个 handsontable,我向其中添加了自定义上下文菜单,而在 firefox 中,本机上下文菜单呈现在我的顶部。一旦我弄清楚如何在 firefox 中的任何地方阻止上下文菜单,我将把它应用到自定义渲染器中的 handsontable

编辑:开始赏金是因为 none 其他 hacks 对我有用,这是一个关于罕见版本的 firefox

的非常模糊的案例

我刚刚在 firefox 中测试了这个,Mac 的 ESR 60.8 并且它有效,你能再检查一下它是否也适合你。

请仔细检查您调用的 preventDefault 事件是否正确,我多次遇到 e 未定义的错误。

我还假设您正在使用来自标签的反应和 post

的语法

class Example extends React.Component {
  render() {
    return (
      <div className="red" onContextMenu={(e) => {
    console.log(e);
    e.preventDefault(); 
    e.stopPropagation(); 
}}>hello click me</div>
    );
  }
}

ReactDOM.render(
    <Example/>,
    document.getElementById('root')
);
.red{
  background: red;
  height: 150px;
  width: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root">
    <!-- This element's contents will be replaced with your component. -->
</div>

最后的手段可能是在元素的 ref 上绑定侦听器。

this.handsontableRef.addEventListener('contextmenu', (e)=> {
  e.preventDefault();
  console.log("open your context menu");
});

在 Firefox 中试过这个,对我有用。分享确切的代码,以便我们也可以在我们这边进行复制。

您需要在捕获阶段剪切菜单打开。

document.addEventListener("contextmenu", function(e) {
    if(e.target.id === "YOUR ELEMENT ID") { // identify your element here. You can use e.target.id, or e.target.className, e.target.classList etc...
        e.preventDefault();
        e.stopPropagation();
    }
}, true) // true means you are executing your function during capture phase

您可以在 componentDidMount 期间或在 React 代码之外设置此代码。

一位同事帮我解决了这个问题。我的工作计算机上预配置的 firefox 设置存在问题。要修复它,我必须在 firefox 中转到 about:config url,然后双击更改 dom.event.contextmenu.enabled 值。这将它从“修改后的布尔值假”更改为“默认布尔值真”。 e.preventDefault() 的预期行为遵循