admin管理员组

文章数量:1397086

I have a table of cells, and I want to be able to create a menu on the point of right click. I have an example of my fiddle here: jsFiddle

Now the ContextMenu class is just a div that I created for this example. As you can see there are no borders to form the actual menu. Now how can I make this menu display at the position my mouse is when I click on one of these cells? Right now it displays under the current table div.

Do I need to mount the menu div under ponentWillMount() ?

I have a table of cells, and I want to be able to create a menu on the point of right click. I have an example of my fiddle here: jsFiddle

Now the ContextMenu class is just a div that I created for this example. As you can see there are no borders to form the actual menu. Now how can I make this menu display at the position my mouse is when I click on one of these cells? Right now it displays under the current table div.

Do I need to mount the menu div under ponentWillMount() ?

Share Improve this question edited Jun 11, 2015 at 18:39 AGE 3,7923 gold badges42 silver badges62 bronze badges asked Jun 11, 2015 at 18:21 orpqKorpqK 2,79513 gold badges51 silver badges81 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

onContextMenu method gives the location of mouse click as e.pageX (left) and e.pageY (top). Based on this coordinates position the context menu absolutely.

Also, instead of coupling ContextMenu ponent's behavior with parent's state, display the ContextMenu ponent always (but hidden). Something like this

var ContextMenu = React.createClass({
    getInitialState: function(){
        return {contextMenuLocation: ''};
    },
    render: function() {
        var location = this.state.contextMenuLocation;
        var contentMenuStyle = {
            display: location ? 'block' : 'none',
            position: 'absolute', 
            left: location ? location.x : 0,
            top: location ? location.y : 0
        };
        return (
            <div id="results" style={contentMenuStyle}>
                Menu here
            </div>
        );
    }
});

Parent ponent's render would look like this

render: function(){
  return (<div>
    .....
    <ContextMenu ref="contextMenu" />
  </div>);
}

Maintain a reference to contextMenu in parent ponent

ponentDidMount: function(){
  this.contextMenu = this.refs.contextMenu;
}

Display it like this

_onContextMenu: function(e) {
    this.contextMenu.setState({
      contextMenuLocation: {'x' : e.pageX, 'y': e.pageY}
    });
    return false;
}

Here is the updated demo http://jsfiddle/dhirajbodicherla/kb3gN/11383/

本文标签: javascriptDisplay a div at the position of mouse clickStack Overflow