使用 React JS 的右键菜单 [英] Right Click Menu using React JS

查看:47
本文介绍了使用 React JS 的右键菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有最佳实践/正确方法来为 React 组件设置右键单击菜单.

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

我目前有这个...

// 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,

谢谢!

推荐答案

更新:

想通了 - 这是你可以做的

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>
}

在渲染中,您可以将一个函数传递给 onContextMenu,以便在此反应组件发生右键单击时使用.

In render you can pass a function to onContextMenu for when a right click occurs for this react component.

这篇关于使用 React JS 的右键菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆