Javascript 使用 React JS 的右键菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28648292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Right Click Menu using React JS
提问by Tom
I'd like to know if there is a best practice/correct way to setup a right-click menu for a React component.
我想知道是否有最佳实践/正确方法来为 React 组件设置右键单击菜单。
I currently have this...
我目前有这个...
// nw is nw.gui from Node-Webkit
componentWillMount: function() {
var menu = new nw.Menu();
menu .append(new nw.MenuItem({
label: 'doSomething',
click: function() {
// doSomething
}
}));
// I'd like to know if this bit can be done in a cleaner/more succinct way...
// BEGIN
var that = this;
addEventListener('contextmenu', function(e){
e.preventDefault();
// Use the attributes property to uniquely identify this react component
// (so different elements can have different right click menus)
if (e.target.attributes[0].nodeValue == that.getDOMNode().attributes[0].nodeValue) {
menu.popup(e.x, e.y);
}
})
// END
},
This works, but it feels a little messy and I was wondering if there was another approach I might be able to use, any information would be greatly appreciated,
这有效,但感觉有点混乱,我想知道是否有另一种方法可以使用,任何信息将不胜感激,
Thanks!
谢谢!
回答by Tom
UPDATE:
更新:
Figured it out - here is what you can do
想通了 - 这是你可以做的
var addMenu;
componentWillMount: function() {
addMenu = new nw.Menu();
addMenu.append(new nw.MenuItem({
label: 'doSomething',
click: function() {
// doSomething
}
}));
},
contextMenu: function(e) {
e.preventDefault();
addMenu.popup(e.clientX, e.clientY);
},
render: function(){
return <button onClick={this.handleClick} onContextMenu={this.contextMenu}>SomethingUseful</button>
}
In render you can pass a function to onContextMenu for when a right click occurs for this react component.
在渲染中,您可以将一个函数传递给 onContextMenu,以便在此反应组件发生右键单击时。
回答by Danko Kozar
There are few things to take care about with popup menus:
使用弹出菜单需要注意以下几点:
- it should be rendered away from its parent and siblings - preferably in an overlay which is the last child of document.body
- special logic should take care that it's always displayed on screen and never cropped by screen edges
- if there is a hierarchy involved, child popups should be aligned to items from previous popup (opener).
- 它应该远离其父级和兄弟级渲染 - 最好在 document.body 的最后一个子级的叠加层中
- 特殊的逻辑应该注意它总是显示在屏幕上并且永远不会被屏幕边缘裁剪
- 如果涉及层次结构,则子弹出窗口应与上一个弹出窗口(开启程序)中的项目对齐。
I created a library which you can use to accomplish all of these:
我创建了一个库,您可以使用它来完成所有这些:

