块编辑器开发文档

💡 云策文档标注

概述

Tooltip 是一个 React 组件,用于在节点获得焦点或被鼠标悬停时渲染浮动帮助文本。如果工具提示超出页面边界,其位置会自动翻转。

关键要点

  • Tooltip 组件通过 children 属性指定锚点元素,仅接受单个子元素。
  • 支持嵌套 Tooltip,但仅最外层的 Tooltip 会被渲染和显示。
  • 提供多种配置属性,如 delay、hideOnClick、placement、shortcut 和 text,用于自定义行为。

代码示例

import { Tooltip } from '@wordpress/components';

const MyTooltip = () => (
    <Tooltip text="More information">
        <div>Hover for more information</div>
    </Tooltip>
);

注意事项

  • children 属性是必需的,且只接受一个 React 元素作为锚点。
  • placement 属性优先于 position 属性使用,后者为遗留方式。
  • shortcut 属性可以是字符串或对象,用于添加可访问的键盘快捷键。

📄 原文内容

Tooltip is a React component to render floating help text relative to a node when it receives focus or it is hovered upon by a mouse. If the tooltip exceeds the bounds of the page in the direction it opens, its position will be flipped automatically.

Usage

Render a Tooltip, passing as a child the element to which it should anchor:

import { Tooltip } from '@wordpress/components';

const MyTooltip = () => (
    <Tooltip text="More information">
        <div>Hover for more information</div>
    </Tooltip>
);

Nested tooltips

In case one or more Tooltip components are rendered inside another Tooltip component, only the tooltip associated to the outermost Tooltip component will be rendered in the browser and shown to the user appropriately. The rest of the nested Tooltip components will simply no-op and pass-through their anchor.

Props

The component accepts the following props:

children: React.ReactElement

The element to which the tooltip should anchor.

NOTE: Accepts only one child element.

  • Required: Yes

delay: number

The amount of time in milliseconds to wait before showing the tooltip.

  • Required: No
  • Default: 700

hideOnClick: boolean

Option to hide the tooltip when the anchor is clicked.

  • Required: No
  • Default: true

placement: 'top' | 'top-start' | 'top-end' | 'right' | 'right-start' | 'right-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end'

Used to specify the tooltip’s placement with respect to its anchor.

  • Required: No
  • Default: 'top'

position: string

Note: use the placement prop instead when possible.

Legacy way to specify the popover’s position with respect to its anchor. Specify y- and x-axis as a space-separated string. Supports 'top', 'middle', 'bottom' y axis, and 'left', 'center', 'right' x axis.

  • Required: No
  • Default: 'top'

shortcut: string | object

An option for adding accessible keyboard shortcuts.

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.

  • Required: No

text: string

The text shown in the tooltip when anchor element is focused or hovered.

  • Required: No