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'));