我想知道是否有一个最佳实践/正确的方式来设置React组件的右键单击菜单.
我目前有这个…
- // 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
- },
这有效,但感觉有点混乱,我想知道是否有另一种方法我可以使用,任何信息将不胜感激,
谢谢!
解决方法
更新:
看出来 – 这是你可以做的
- 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>
- }
在渲染中,您可以将函数传递给onContextMenu,以便在此反应组件发生右击时.