Right Click Menu using React JS

谁都会走 提交于 2019-12-31 09:17:13

问题


I'd like to know if there is a best practice/correct way to setup a right-click menu for a React component.

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!


回答1:


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.




回答2:


There are few things to take care about with popup menus:

  1. it should be rendered away from its parent and siblings - preferably in an overlay which is the last child of document.body
  2. special logic should take care that it's always displayed on screen and never cropped by screen edges
  3. if there is a hierarchy involved, child popups should be aligned to items from previous popup (opener).

I created a library which you can use to accomplish all of these:

http://dkozar.github.io/react-data-menu/



来源:https://stackoverflow.com/questions/28648292/right-click-menu-using-react-js

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