小编典典

使用React JS右键单击菜单

reactjs

我想知道是否有最佳实践/正确的方法来为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
},

可以,但是感觉有点混乱,我想知道是否还有其他方法可以使用,任何信息将不胜感激,

谢谢!


阅读 1368

收藏
2020-07-22

共1个答案

小编典典

更新:

想通了-这是您可以做的

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,以使该react组件发生右键单击。

2020-07-22