块编辑器开发文档

💡 云策文档标注

概述

MenuItem 是一个用于渲染按钮的组件,通常与 DropdownMenu 组件结合使用,支持多种属性来自定义菜单项的行为和外观。

关键要点

  • MenuItem 是 WordPress 组件库中的一部分,主要用于创建菜单项按钮。
  • 它接受多种 props,如 children、disabled、info、icon、isSelected 等,以控制其功能和样式。
  • 通过 role prop 可以指定菜单项的角色,如 'menuitem'、'menuitemradio' 或 'menuitemcheckbox',以适应不同的交互需求。

代码示例

import { useState } from 'react';
import { MenuItem } from '@wordpress/components';

const MyMenuItem = () => {
    const [ isActive, setIsActive ] = useState( true );

    return (
        <MenuItem
            icon={ isActive ? 'yes' : 'no' }
            isSelected={ isActive }
            onClick={ () => setIsActive( ( state ) => ! state ) }
        >
            Toggle
        </MenuItem>
    );
};

注意事项

  • isSelected prop 仅在 role 为 "menuitemcheckbox" 或 "menuitemradio" 时生效。
  • shortcut prop 可以是字符串或对象,对象形式需包含 display 和 ariaLabel 属性。
  • 所有未列出的 props 会传递给底层的 Button 组件。

📄 原文内容

MenuItem is a component which renders a button intended to be used in combination with the DropdownMenu component.

Usage

import { useState } from 'react';
import { MenuItem } from '@wordpress/components';

const MyMenuItem = () => {
    const [ isActive, setIsActive ] = useState( true );

    return (
        <MenuItem
            icon={ isActive ? 'yes' : 'no' }
            isSelected={ isActive }
            onClick={ () => setIsActive( ( state ) => ! state ) }
        >
            Toggle
        </MenuItem>
    );
};

Props

MenuItem supports the following props. Any additional props are passed through to the underlying Button.

children

  • Type: Element
  • Required: No

Element to render as child of button.

disabled

  • Type: boolean
  • Required: No

Refer to documentation for Button’s disabled prop.

info

  • Type: string
  • Required: No

Text to use as description for button text.

Refer to documentation for label.

icon

  • Type: string
  • Required: No

Refer to documentation for Button’s icon prop.

iconPosition

  • Type: string
  • Required: No
  • Default: 'right'

Determines where to display the provided icon.

isSelected

  • Type: boolean
  • Required: No

Whether or not the menu item is currently selected. isSelected is only taken into account when the role prop is either "menuitemcheckbox" or "menuitemradio".

shortcut

  • Type: string or object
  • Required: No

If shortcut is a string, it is expecting the display text. If shortcut is an object, it will accept the properties of display (string) and ariaLabel (string).

role

  • Type: string
  • Require: No
  • Default: 'menuitem'

Aria Spec. If you need to have selectable menu items use menuitemradio for single select, and menuitemcheckbox for multiselect.

suffix

  • Type: Element
  • Required: No

Allows for markup other than icons or shortcuts to be added to the menu item.