React 自定义右键菜单

  • 核心步骤
    • window绑定contextmenu方法展示自定义菜单
    • 阻止浏览器本身的右键菜单

代码实现

RightMent.jsx
import React, { useMemo } from "react";
import { useHistory, useModel } from "umi";
import styles from "./index.module.less";

const RightMenu = () => {
  const { qbb } = useModel("qbb");
  const history = useHistory();
  return useMemo(
    () => (
      <div
        className={styles.Menu}
        style={{
          top: qbb.top,
          left: qbb.left,
          display: qbb.menu ? "block" : "none",
        }}>
        <div className={styles.MenuContent}>
          <div className={styles.MenuItem} onClick={() => history.push("/")}>
            返回首页
          </div>
          <div className={styles.MenuItem} onClick={() => history.go(0)}>
            刷新
          </div>
        </div>
      </div>
    ),
    [qbb.top, qbb.left, qbb.menu]
  );
};

export default RightMenu;
index.module.less
.Menu {
  position: fixed;
  z-index: 9999;
  width: 200px;
  min-height: 300px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24),
    0 0 10px rgba(128, 128, 128, 0.63);
  .MenuContent {
    padding: 4px 0;
  }
  .MenuItem {
    padding: 8px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
    &:hover {
      background-color: gray;
      color: #fff;
    }
  }
}
入口文件
import React, { useEffect } from "react";
import { useModel } from "umi";
import RightMenu from "@/components/RightMenu";

const Index = ({ children }) => {
  const { setQbb } = useModel("qbb");
  useEffect(() => {
    window.addEventListener("click", () => setQbb({ menu: false }));
    window.addEventListener("contextmenu", (e) => {
      setQbb({ top: e.clientY, left: e.clientX, menu: true });
      e.preventDefault();
    });
  }, []);
  return (
    <>
      {children} <RightMenu />
    </>
  );
};

export default Index;

已知问题

没有做边界判断,也就是在界面最右边点击时菜单有一部分不可见,可以做优化