react添加右键点击事件

1.在HTML里面支持contextmenu事件(右键事件)。所以需要在组建加载完时添加此事件,销毁组建时移除此事件。

2. 需要增加一个state,名称为visible,用来控制菜单是否显示。在_handleContextMenu(右键事件)里面,它被设置为true,从而可以显示出来。那么,当鼠标点击其它位置或者滚动的时候,需要把 它设置为false。

例如代码:

class ContextMenu extends React.Component {

constructor(props) {

super(props);

this.state = {

visible: false,

};

}

componentDidMount() {

document.addEventListener('contextmenu', this._handleContextMenu);

document.addEventListener('click', this._handleClick);

document.addEventListener('scroll', this._handleScroll);

};

componentWillUnmount() {

document.removeEventListener('contextmenu', this._handleContextMenu);

document.removeEventListener('click', this._handleClick);

document.removeEventListener('scroll', this._handleScroll);

}

_handleContextMenu = (event) => {

// this.setState({ visible:false });//当点击其他地方右键时可以根据需求来判断是否需要先关闭菜单

event.preventDefault();

this.setState({ visible: true });

const clickX = event.clientX;

const clickY = event.clientY; //事件发生时鼠标的Y坐标

const screenW = window.innerWidth; //文档显示区的宽度

const screenH = window.innerHeight;

const rootW = this.root.offsetWidth; //右键菜单本身元素的宽度

const rootH = this.root.offsetHeight;

// right为true,说明鼠标点击的位置到浏览器的右边界的宽度可以放contextmenu。

// 否则,菜单放到左边。 // top和bottom,同理。

const right = (screenW - clickX) > rootW;

const left = !right;

const top = (screenH - clickY) > rootH;

const bottom = !top;

if (right) {

this.root.style.left = `${clickX + 15}px`;

}

if (left) {

this.root.style.left = `${clickX - rootW - 15}px`;

}

if (top) {

this.root.style.top = `${clickY + 15}px`;

}

if (bottom) {

this.root.style.top = `${clickY - rootH - 15}px`;

}

};

_handleClick = (event) => {

const { visible } = this.state;

const wasOutside = !(event.target.contains === this.root);

if (wasOutside && visible) this.setState({ visible: false, });

};

_handleScroll = () => {

const { visible } = this.state;

if (visible) this.setState({ visible: false, });

};

render() {

const { visible } = this.state;

return

{ visible?

<div ref={ref => {this.root = ref}} className="contextMenu">

<div>右键菜单内容</div>

</div>: null}

};

}

ReactDOM.render(<ContextMenu />, document.getElementById('root'));