Перейти к основному содержанию

Class: MenuItem

Class: MenuItem

Добавляет элементы в основное меню и контекстное меню приложения.

Процесс: Главный

Просмотрите Menu для примеров использования.

new MenuItem(options)

  • options Object
    • click Function (optional) - Will be called with click(menuItem, browserWindow, event) when the menu item is clicked.
    • role string (optional) - Can be undo, redo, cut, copy, paste, pasteAndMatchStyle, delete, selectAll, reload, forceReload, toggleDevTools, resetZoom, zoomIn, zoomOut, toggleSpellChecker, togglefullscreen, window, minimize, close, help, about, services, hide, hideOthers, unhide, quit, showSubstitutions, toggleSmartQuotes, toggleSmartDashes, toggleTextReplacement, startSpeaking, stopSpeaking, zoom, front, appMenu, fileMenu, editMenu, viewMenu, shareMenu, recentDocuments, toggleTabBar, selectNextTab, selectPreviousTab, mergeAllWindows, clearRecentDocuments, moveTabToNewWindow or windowMenu - Define the action of the menu item, when specified the click property will be ignored. Смотрите роли.
    • type string (optional) - Can be normal, separator, submenu, checkbox or radio.
    • label string (optional)
    • sublabel string (optional)
    • toolTip string (optional) macOS - Hover text for this menu item.
    • accelerator Accelerator (опционально)
    • icon (NativeImage | string) (optional)
    • enabled boolean (optional) - If false, the menu item will be greyed out and unclickable.
    • acceleratorWorksWhenHidden boolean (optional) macOS - default is true, and when false will prevent the accelerator from triggering the item if the item is not visible.
    • visible boolean (optional) - If false, the menu item will be entirely hidden.
    • checked boolean (optional) - Should only be specified for checkbox or radio type menu items.
    • registerAccelerator boolean (optional) Linux Windows - If false, the accelerator won't be registered with the system, but it will still be displayed. Defaults to true.
    • sharingItem SharingItem (optional) macOS - The item to share when the role is shareMenu.
    • submenu (MenuItemConstructorOptions[] | Menu) (опционально) - Необходимо указать для submenu типы элементов меню. Если submenu указано, то type: 'submenu' может быть опущен. Если значение не является Menu то оно будет автоматически преобразовано в значение Menu.buildFromTemplate.
    • id string (optional) - Unique within a single menu. If defined then it can be used as a reference to this item by the position attribute.
    • before string[] (optional) - Inserts this item before the item with the specified label. Если указанный элемент не существует, то элемент будет вставлен в конец меню. Кроме того, подразумевается, что рассматриваемый элемент меню размещен в той же "группе", что и сам элемент.
    • after string[] (optional) - Inserts this item after the item with the specified label. Если ссылаемый элемент не существует, тогда элемент будет вставлен в конец меню.
    • beforeGroupContaining string[] (optional) - Provides a means for a single context menu to declare the placement of their containing group before the containing group of the item with the specified label.
    • afterGroupContaining string[] (optional) - Provides a means for a single context menu to declare the placement of their containing group after the containing group of the item with the specified label.

Примечание: acceleratorWorksWhenHidden указан только как macOS потому, что accelerators всегда работают, когда элементы скрыты в Windows и Linux. Эта опция доступна пользователям для того, чтобы дать им возможность отключить ее, так как это возможно в родной macOS разработке.

Роли

Роли позволяют элементам класса menu иметь заранее определенные поведения.

Лучше всего указать role для любого элемента меню, который соответствует стандартной роли, а не пытаться вручную реализовать поведение в функции click. Встроенное поведение role даст наилучшую нативную возможность использования.

Значения label и accelerator необязательны при использовании role и по умолчанию будут присваиваться для каждой для каждой платформы.

Каждый элемент меню должен иметь role или label, или в случае разделителя type.

Свойство role может иметь следующие значения:

  • undo - Отменить
  • about - Trigger a native about panel (custom message box on Window, which does not provide its own).
  • redo - Восстановить
  • cut - Вырезать
  • copy - Копировать
  • paste - Вставить
  • pasteAndMatchStyle - Вставить и применить стиль
  • selectAll - Выделить все
  • delete - Удалить
  • minimize - Свернуть текущее окно.
  • close - Закрыть текущее окно.
  • quit - Выйти из приложения.
  • reload - Перезагрузить текущее окно.
  • forceReload - Перезагрузить текущее окно, игнорировать кэш.
  • toggleDevTools - Включить инструмент разработчика для текущего окна.
  • togglefullscreen -Включить полноэкранный режим для текущего окна.
  • resetZoom - Сброс измененного масштаба страницы до исходного размера.
  • zoomIn - Увеличение масштаба страницы на 10%.
  • zoomOut - Уменьшение масштаба страницы на 10%.
  • toggleSpellChecker - Enable/disable builtin spell checker.
  • fileMenu - Полное меню "Файл" по умолчанию (Закрыть/Выйти)
  • editMenu - Whole default "Edit" menu (Undo, Copy, etc.).
  • viewMenu - Полное меню "Вид" по умолчанию (перезагрузка, переключение инструментов разработчика и т. д.)
  • windowMenu - Полное меню "Окно" по умолчанию (Свернуть, масштаб и т. д.).

На macOS доступны следующие дополнительные роли:

  • appMenu - Полное меню "App" по умолчанию (О программе, службах и т. д.)
  • hide - Map to the hide action.
  • hideOthers - Map to the hideOtherApplications action.
  • unhide - Map to the unhideAllApplications action.
  • showSubstitutions - Map to the orderFrontSubstitutionsPanel action.
  • toggleSmartQuotes - Map to the toggleAutomaticQuoteSubstitution action.
  • toggleSmartDashes - Map to the toggleAutomaticDashSubstitution action.
  • toggleTextReplacement - Map to the toggleAutomaticTextReplacement action.
  • startSpeaking - Map to the startSpeaking action.
  • stopSpeaking - Map to the stopSpeaking action.
  • front - Map to the arrangeInFront action.
  • zoom - Map to the performZoom action.
  • toggleTabBar - Map to the toggleTabBar action.
  • selectNextTab - Map to the selectNextTab action.
  • selectPreviousTab - Map to the selectPreviousTab action.
  • mergeAllWindows - Map to the mergeAllWindows action.
  • moveTabToNewWindow - Map to the moveTabToNewWindow action.
  • window - The submenu is a "Window" menu.
  • help - The submenu is a "Help" menu.
  • services - Подменю меню "Сервисы". This is only intended for use in the Application Menu and is not the same as the "Services" submenu used in context menus in macOS apps, which is not implemented in Electron.
  • recentDocuments - The submenu is an "Open Recent" menu.
  • clearRecentDocuments - Map to the clearRecentDocuments action.
  • shareMenu - The submenu is share menu. The sharingItem property must also be set to indicate the item to share.

При задании role на macOS, label и accelerator являются единственными параметрами, которые влияют на пункт меню. Все остальные параметры будут проигнорированы. Нижний регистр role, например toggledevtools, все еще поддерживается.

Note: The enabled and visibility properties are not available for top-level menu items in the tray on macOS.

Свойства экземпляра

Для экземпляров MenuItem доступны следующие свойства:

A string indicating the item's unique id, this property can be dynamically changed.

A string indicating the item's visible label.

A Function that is fired when the MenuItem receives a click event. It can be called with menuItem.click(event, focusedWindow, focusedWebContents).

Menu (опционально), содержащие подменю пункты, если таковые имеются.

A string indicating the type of the item. Can be normal, separator, submenu, checkbox or radio.

A string (optional) indicating the item's role, if set. Can be undo, redo, cut, copy, paste, pasteAndMatchStyle, delete, selectAll, reload, forceReload, toggleDevTools, resetZoom, zoomIn, zoomOut, toggleSpellChecker, togglefullscreen, window, minimize, close, help, about, services, hide, hideOthers, unhide, quit, startSpeaking, stopSpeaking, zoom, front, appMenu, fileMenu, editMenu, viewMenu, shareMenu, recentDocuments, toggleTabBar, selectNextTab, selectPreviousTab, mergeAllWindows, clearRecentDocuments, moveTabToNewWindow or windowMenu

An Accelerator (optional) indicating the item's accelerator, if set.

An Accelerator | null indicating the item's user-assigned accelerator for the menu item.

Note: This property is only initialized after the MenuItem has been added to a Menu. Either via Menu.buildFromTemplate or via Menu.append()/insert(). Accessing before initialization will just return null.

A NativeImage | string (optional) indicating the item's icon, if set.

A string indicating the item's sublabel.

A string indicating the item's hover text.

A boolean indicating whether the item is enabled, this property can be dynamically changed.

A boolean indicating whether the item is visible, this property can be dynamically changed.

A boolean indicating whether the item is checked, this property can be dynamically changed.

Элемент меню checkbox будет включать и выключать свойство checked при его выборе.

Radio пункт меню включит его свойство checked при нажатии, и отключит это свойство для всех смежных пунктов в том же меню.

Вы можете добавить функцию click для дополнительного поведения.

A boolean indicating if the accelerator should be registered with the system or just displayed.

This property can be dynamically changed.

A SharingItem indicating the item to share when the role is shareMenu.

This property can be dynamically changed.

A number indicating an item's sequential unique id.

Меню, частью которого является элемент.