Обзор
ИспользуйтеTooltip для краткого пояснения элемента управления или усечённого текста. Необходимая информация должна быть видимой, элементы управления должны иметь доступное имя; используйте Popover, если содержимое включает ссылки, кнопки или другие элементы управления.
Использование
children. Нативные элементы получают атрибуты триггера, обработчики событий и ref напрямую. Пользовательские компоненты-триггеры должны перенаправлять их все. Элемент-обёртка также работает с компонентом, который не перенаправляет все свойства триггера.
При наведении всплывающая подсказка открывается через delay миллисекунд; по умолчанию используется 600. При фокусе с клавиатуры она открывается немедленно. По умолчанию closeDelay равен 0; наведение на всплывающее окно сохраняет его открытым, если не задан disableHoverablePopup. Escape закрывает её.
Управляемое состояние
Используйтеopen и onOpenChange вместе, когда приложению принадлежит управление видимостью. Используйте defaultOpen только для задания начальной видимости неуправляемой всплывающей подсказки.
Расширенное содержимое и композиция
Сокращённый вариант принимаетdescription и startIcon наряду с content. Пользовательское содержимое в виде узла отображается как задано, если описание или значок не запрашивают макет заголовка.
Tooltip.Body. Явно соберите портал, позиционирование, всплывающее окно и необязательную стрелку. Popup отображает свои дочерние элементы в переданном виде; Body предоставляет тот же макет с заголовком, описанием и декоративной иконкой, что и сокращённый вариант.
Tooltip.Body принимает необязательные дочерние элементы заголовка, а также узлы description и startIcon. Для заголовков используется средняя насыщенность; для описаний — дополнительный цвет tooltip; переносы строк сохраняются, а длинный текст переносится. Для tooltip только с описанием не добавляйте дочерние элементы заголовка. Значок является декоративным и отображается только при наличии заголовка. Body не добавляет роль tooltip, стилизацию popup, изменение размера или позиционирование. Поддерживается произвольное содержимое Popup. При типизации обёртки импортируйте TooltipBodyProps из twenty-ui/primitives/surfaces.
Каждая DOM-часть принимает нативные свойства, ref и композицию render с элементом или обратным вызовом. Нативные свойства верхнего уровня сокращённого варианта, render и ref нацелены на Popup. Используйте triggerProps, positionerProps и portalProps для настройки других целей; они переопределяют значения по умолчанию сокращённого варианта. Дочерние элементы предоставляют элемент отображения триггера по умолчанию. Обе формы сохраняют управляемое/неуправляемое состояние Root и сведения о событиях обратных вызовов Base UI, включая отмену, причину, исходное событие и активный триггер.
Tooltip.createHandle\<TPayload>() подключает отсоединённые триггеры к любой из форм через handle. Дочерние элементы составного Root или content сокращённого варианта могут быть функцией, получающей типизированную активную полезную нагрузку. Tooltip.Handle и публичный тип TooltipHandle предоставляют контракт установленного дескриптора. Дескрипторы поддерживают императивные open(triggerId) и close(), пока их Root смонтирован.
Миграция
Заменитеcontent={<Tooltip.Content description={description} startIcon={icon}>title</Tooltip.Content>} на content={title} description={description} startIcon={icon}. При составном использовании применяйте Tooltip.Body для общего макета заголовка и описания либо создайте собственное содержимое. Tooltip.Content и TooltipContentProps удалены.
Существующие свойства позиционирования составного Popup переносятся в Positioner. Оберните его в Portal, перенесите container и keepMounted в Portal, оставьте maxWidth в Popup и замените arrow дочерним элементом Arrow. При необходимости явно сохраните прежние интервалы с помощью sideOffset={10}. Составной Positioner сохраняет значение Base UI sideOffset={0}. Обе формы по умолчанию ограничивают Popup до 300 пикселей.
Отключённые элементы управления
Нативные отключённые кнопки не могут получать фокус с клавиатуры. Оберните такую кнопку в фокусируемый триггер, чтобы пользователи могли узнать, почему действие недоступно.disabled для сокращённого варианта или Root отключает саму всплывающую подсказку. disabled триггера отключает взаимодействие со всплывающей подсказкой этого триггера. Отключайте нативный элемент управления через его собственные свойства или элемент отображения Trigger.
Размещение и переполняющий текст
Для сокращённой формы по умолчанию используютсяside="top", align="center" и sideOffset={10}. Как сокращённые, так и составные всплывающие подсказки имеют максимальную ширину 300 пикселей, ограниченную доступным пространством рядом с якорем. Передайте maxWidth в сокращённую подсказку или Tooltip.Popup, чтобы выбрать другое максимальное значение, включая более широкие предварительные просмотры. Встроенные стили всплывающих окон остаются доступными для настройки пользовательского размера. Размещение корректируется в соответствии с доступным пространством. Открытая всплывающая подсказка скрывается, когда её якорь прокручивается за пределы видимости, в том числе за пределы контейнера прокрутки. Используйте arrow для стрелки и container, чтобы переопределить назначение портала темы; см. темизацию.
Используйте OverflowingTextWithTooltip, когда текстовая метка должна показывать полное значение только при усечении. Его существующие свойства text, tooltipContent и tooltipPlace остаются доступными.
Свойства
Справочник генерируется из публичных типов компонентов. Также принимаются нативные атрибуты всплывающего окна и обработчики событий.A ref to imperative actions.
unmount: Ends the closing phase of the tooltip after an externally controlled closing animation finishes. CallpreventUnmountOnClose()inonOpenChangefirst, otherwise the tooltip completes closing on its own. Whether it leaves the DOM is decided bykeepMountedon the portal.close: Closes the tooltip imperatively when called.
Alignment relative to the trigger. Defaults to center.
Element | VirtualElement | RefObject<Element | null> | (() => Element | VirtualElement | null) | null
An explicit positioning anchor for the popup.
A single trigger element. Custom components must forward their ref, native attributes, and event handlers.
Determines how to handle collisions when positioning the popup.
side controls overflow on the preferred placement axis (top/bottom or left/right):'flip': keep the requested side when it fits; otherwise try the opposite side (topandbottom, orleftandright).'shift': never change side; keep the requested side and move the popup within the clipping boundary so it stays visible.'none': do not correct side-axis overflow.
align controls overflow on the alignment axis (start/center/end):'flip': keep side, but swapstartandendwhen the requested alignment overflows.'shift': keep side and requested alignment, then nudge the popup along the alignment axis to fit.'none': do not correct alignment-axis overflow.
fallbackAxisSide controls fallback behavior on the perpendicular axis when the
preferred axis cannot fit:'start': allow perpendicular fallback and try the logical start side first (topbeforebottom, orleftbeforerightin LTR).'end': allow perpendicular fallback and try the logical end side first (bottombeforetop, orrightbeforeleftin LTR).'none': do not fallback to the perpendicular axis.
side is 'shift', explicitly setting align only supports 'shift' or 'none'.
If align is omitted, it defaults to 'flip'.An element or a rectangle that delimits the area that the popup is confined to.
Portal destination. Defaults to the current theme container.
Supplementary content, or a function receiving the active trigger payload. Strings and numbers use the shorthand title layout.
ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
defaultOpen prop to create an initially open tooltip.Whether to disable the popup from tracking any layout shift of its positioning anchor.
Maximum popup width. Defaults to 300 pixels and is capped by the space available beside the anchor.
Receives the requested open state and unchanged Base UI event details, including reason, event, trigger and cancel().
Event handler called after any animations complete when the tooltip is opened or closed.
Full Portal props, including native props, ref and render. Overrides shorthand portal defaults.
Full Positioner props, including native props, ref and render. Overrides shorthand placement defaults.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPopupState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.Preferred side of the trigger. Defaults to top and may change to avoid collisions.
Whether to maintain the popup in the viewport after
the anchor element was scrolled out of view.
Inline styles for the popup.
Determines which axis the tooltip should track the cursor on.
ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
open prop to create a controlled tooltip.
There’s no need to specify this prop when the tooltip is uncontrolled (that is, when the open prop is not set).Full Trigger props, including native props, ref, render and payload. Overrides the shorthand trigger defaults.
Tooltip.Root
A ref to imperative actions.
unmount: Ends the closing phase of the tooltip after an externally controlled closing animation finishes. CallpreventUnmountOnClose()inonOpenChangefirst, otherwise the tooltip completes closing on its own. Whether it leaves the DOM is decided bykeepMountedon the portal.close: Closes the tooltip imperatively when called.
Parts or a render function receiving the active trigger payload. Root renders no DOM node.
Whether the tooltip is initially open.To render a controlled tooltip, use the
open prop instead.ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
defaultOpen prop to create an initially open tooltip.Receives the requested open state and unchanged Base UI event details, including reason, event, trigger and cancel().
Event handler called after any animations complete when the tooltip is opened or closed.
Determines which axis the tooltip should track the cursor on.
ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
open prop to create a controlled tooltip.
There’s no need to specify this prop when the tooltip is uncontrolled (that is, when the open prop is not set).Tooltip.Trigger
CSS class applied to the element, or a function that
returns a class based on the component’s state.
How long to wait before opening the tooltip on hover. Specified in milliseconds.
Disables tooltip interaction for this trigger without disabling its native element.
((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<...>)) | null
Ref to the rendered trigger element, a button by default.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipTriggerState>
Composes a native element or a component that forwards attributes, handlers and ref.
Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Portal
CSS class applied to the element, or a function that
returns a class based on the component’s state.
Portal destination. Defaults to the current theme container, then the document body.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPortalState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Positioner
How to align the popup relative to the specified side.
Additional offset along the alignment axis in pixels.
Also accepts a function that returns the offset to read the dimensions of the anchor
and positioner elements, along with its side and alignment.The function takes a
data object parameter with the following properties:data.anchor: the dimensions of the anchor element with propertieswidthandheight.data.positioner: the dimensions of the positioner element with propertieswidthandheight.data.side: which side of the anchor element the positioner is aligned against.data.align: how the positioner is aligned relative to the specified side.
Element | VirtualElement | RefObject<Element | null> | (() => Element | VirtualElement | null) | null
An element to position the popup against.
By default, the popup will be positioned against the trigger.
Minimum distance to maintain between the arrow and the edges of the popup.Use it to prevent the arrow element from hanging out of the rounded corners of a popup.
CSS class applied to the element, or a function that
returns a class based on the component’s state.
Determines how to handle collisions when positioning the popup.
side controls overflow on the preferred placement axis (top/bottom or left/right):'flip': keep the requested side when it fits; otherwise try the opposite side (topandbottom, orleftandright).'shift': never change side; keep the requested side and move the popup within the clipping boundary so it stays visible.'none': do not correct side-axis overflow.
align controls overflow on the alignment axis (start/center/end):'flip': keep side, but swapstartandendwhen the requested alignment overflows.'shift': keep side and requested alignment, then nudge the popup along the alignment axis to fit.'none': do not correct alignment-axis overflow.
fallbackAxisSide controls fallback behavior on the perpendicular axis when the
preferred axis cannot fit:'start': allow perpendicular fallback and try the logical start side first (topbeforebottom, orleftbeforerightin LTR).'end': allow perpendicular fallback and try the logical end side first (bottombeforetop, orrightbeforeleftin LTR).'none': do not fallback to the perpendicular axis.
side is 'shift', explicitly setting align only supports 'shift' or 'none'.
If align is omitted, it defaults to 'flip'.An element or a rectangle that delimits the area that the popup is confined to.
Whether to disable the popup from tracking any layout shift of its positioning anchor.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPositionerState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.Preferred physical or logical side of the anchor. Defaults to top.
Distance from the anchor. Defaults to 0 in compound usage. Accepts a number or positioning function.
Whether to maintain the popup in the viewport after
the anchor element was scrolled out of view.
Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Popup
CSS class applied to the element, or a function that
returns a class based on the component’s state.
Maximum popup width. Defaults to 300 pixels and is capped by the space available beside the anchor.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPopupState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Body
Optional title content, displayed with medium weight. Omit it for a description-only tooltip.
Composes the body root through an element or render callback while preserving its layout and content.
Tooltip.Arrow
CSS class applied to the element, or a function that
returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipArrowState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Viewport
CSS class applied to the element, or a function that
returns a class based on the component’s state.
Ref to the content-transition div. Useful when several triggers share changing content.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipViewportState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Provider
Tooltips sharing delay, closeDelay and timeout configuration. Provider renders no DOM node.