Skip to content

右键菜单

在渲染进程中使用

  1. 引入相应的包

    js
    const { remote } = window.require('electron')
    const { Menu, MenuItem } = remote
  2. 创建菜单

    js
    const menu = Menu()
    menu.append(new MenuItem({
        label: '标签',
        click: () => { /* 要执行的事件 */ }
    }))
  3. 调用弹出菜单

    js
    window.addEventListener('contextmenu', () => {
        menu.popup({ window: remote.getCurrentWindow() })
    })

自定义 hooks 的封装

hooks

typescript
import { useEffect, useRef, MutableRefObject } from 'react'
const { remote } = window.require('electron')
const { Menu, MenuItem } = remote

// MenuItem的类型定义
export interface IMenuItem {
    label: string;
    click: () => void;
}
/**
	itemArr: 菜单项
	containSelector: 只有在某个box(使用 selector 定位)内右键才会弹出菜单
	
	return: null || 被右键的Element
*/
const useContextMenu = (itemArr: IMenuItem[], containSelector?: string, ): MutableRefObject<Element | null> => {
    const element = useRef<Element | null>(null) // 被右键的Element
    useEffect(() => {
        // 循环插入菜单中
        const menu = new Menu()
        itemArr.forEach(item => {
            menu.append(new MenuItem(item))
        })
        // 只有在特定box中点击才触发菜单栏弹出
        const handleContextMenu = (e: MouseEvent) => {
            if (containSelector && document.querySelector(containSelector)?.contains(e.target as Element)) {
                element.current = e.target as Element
                menu.popup({ window: remote.getCurrentWindow() })
            }
        }
        window.addEventListener('contextmenu', handleContextMenu)
        // 注销事件监听
        return () => {
            window.removeEventListener('contextmenu', handleContextMenu)
        }
    }, [itemArr, containSelector])
    return element
}

export default useContextMenu

使用例子

js
import useContextMenu from '../hooks/useContextMenu'

const clickElement = useContextMenu([
 {
     label: '打开',
     click: () => { /*打开*/ }
 },{
     label: '删除',
     click: () => { /*删除事件*/ }
 }
], '.parent-container')