工具提示
Mantine Core 的独立组件,请不要替换为 JGuang UI/Base UI 的同名 API。
安装
npm install @mantine/core@9.7.1 @mantine/hooks@9.7.1
入口引入 @mantine/core/styles.css,并在根组件使用 MantineProvider;通过 forceColorScheme 同步深浅色主题。
使用与验证
在左侧选择组件,在预览中操作它的状态;使用“查看代码”检查真实源码。安装后执行类型检查和构建,再验证键盘焦点、手机布局与深浅色主题。
来源
https://github.com/mantinedev/mantine/tree/f0e2bc6d28b0f0b8aaefb5b859937bf77f539df7 MIT 许可证;不包括付费内容。下方提供上游英文参考内容,中文使用指南已适配;上游详细参考暂保留英文。
版本与兼容性
固定的 Mantine Core 9.7.1 要求 React 和 React DOM 满足 ^19.2.0,并配套 @mantine/hooks@9.7.1。此条件来自实际 npm 包的 peerDependencies。React 18 或其他不兼容版本不能强行安装;先向项目负责人说明升级影响并确认方案,不使用 --force/--legacy-peer-deps 掩盖冲突。入口的原生 Provider 开启 theme.respectReducedMotion,并用 forceColorScheme 控制深浅色。
适用场景
在悬停或聚焦时展示简短提示。
本地示例使用的原生参数
以下参数由本地、经过类型检查的 JSX 示例提取,按所属组件区分。不是全部属性清单;完整签名和继承关系见下方固定源码参考。
| 组件参数 | 说明 |
|---|---|
Tooltip.label | 可见标签或当前组件的标签内容。 |
交互与状态检查
当前场景:默认。切换支持的禁用、错误或只读场景后检查真实行为;无此原生状态的组件不会被强行添加统一属性。验证键盘焦点和退出方式,修改值后按原生回调签名连接业务状态。
业务接入边界
示例内容和状态仅保存在本地,不提供服务端持久化、授权或数据请求。静态展示组件不应被当作已完成的业务流程。
宿主配置
先安装固定版本 @mantine/core 和 @mantine/hooks,在入口引入 @mantine/core/styles.css,并使用 MantineProvider。示例的 theme 和 variant 是 JGuang 编写的宿主参数,不是所有原生组件都接受的统一 API;通过 forceColorScheme 同步应用主题。源码面板中的原生实现仅供阅读,使用 npm 导出,不要单独复制内部实现。此批只覆盖 Core,不包括日期、图表和表单扩展包。上游详细说明保留英文,不宣称全文中文化。
可运行用法
以下代码使用资源原生 API;不是把其他设计系统的同名组件替换进来。
import { useState } from 'react';
import * as M from '@mantine/core';
import '@mantine/core/styles.css';
function ComponentPreview({ variant = 'Default' }: { variant?: string }) {
return <M.Tooltip label="A helpful hint"><M.Button>Hover or focus</M.Button></M.Tooltip>;
}
export default function Example({ variant = 'Default', theme = 'light' }: { variant?: string; theme?: 'light' | 'dark' }) {
return <M.MantineProvider forceColorScheme={theme} theme={{ respectReducedMotion: true }}><ComponentPreview variant={variant} /></M.MantineProvider>;
}
可用状态与示例
默认
示例遵循 Mantine 原生 API。支持多状态的输入组件可将示例中的 variant 改为 Disabled、Invalid 或 Read only;这些只是示例标签,不是新增的组件属性。改造时保留组件要求的数据、受控值、store 和复合子组件结构。
Usage
Tooltip children
Tooltip requires an element or a component as a single child – strings, fragments, numbers and multiple elements/components are not supported and will throw an error. Custom components must provide a prop to get the root element ref; all Mantine components support ref out of the box.
import { Badge, Tooltip } from '@mantine/core';
function Demo() {
return (
<>
<Tooltip label="OK">
<button>Native button – ok</button>
</Tooltip>
<Tooltip label="OK">
<Badge>Mantine component – ok</Badge>
</Tooltip>
<Tooltip label="Throws">
Raw string, NOT OK – will throw an error
</Tooltip>
{/* Number, NOT OK – will throw an error */}
<Tooltip label="Throws">{2}</Tooltip>
<Tooltip label="Throws">
<>Fragment, NOT OK, will throw an error</>
</Tooltip>
<Tooltip label="Throws">
<div>More than one node</div>
<div>NOT OK, will throw an error</div>
</Tooltip>
</>
);
}
Tooltip target
The target prop is an alternative to children. It accepts a string (selector),
an HTML element or a ref object with an HTML element. Use the target prop when you do
not render the tooltip target as a JSX element.
Example of using the target prop with a string selector:
Hide detached
Use the hideDetached prop to configure how the tooltip behaves when the target
element is removed from the DOM, hidden with display: none, or scrolled out of
the viewport or of a scrollable container that clips it.
By default, hideDetached is enabled – the tooltip is hidden with the target element.
You can change this behavior with hideDetached={false}.
Note that hideDetached has no effect on Tooltip.Floating –
it is positioned relative to the mouse pointer rather than to a target element.
In test environments based on jsdom (Jest, Vitest) every element reports a zero-size rectangle,
so the target is always considered detached and the tooltip is hidden. Set env="test" on
MantineProvider in your test wrapper, as described in the
Jest and Vitest guides, or pass hideDetached={false} –
otherwise hideDetached detection is disabled only in the test environment.
To see the difference, try to scroll the root element of the following demo:
Required ref prop
Custom components that are rendered inside Tooltip are required to support ref prop:
// Example of code that WILL NOT WORK
import { Tooltip } from '@mantine/core';
function MyComponent() {
return <div>My component</div>;
}
// This will not work – MyComponent does not support ref
function Demo() {
return (
<Tooltip label="Does not work">
<MyComponent />
</Tooltip>
);
}
The component must support ref prop:
// Example of code that will work
import { Tooltip } from '@mantine/core';
const MyComponent = ({ ref, ...props }) => (
<div ref={ref} {...props}>
My component
</div>
);
// Works correctly – ref is forwarded
function Demo() {
return (
<Tooltip label="Works fine">
<MyComponent />
</Tooltip>
);
}
Color
Offset
Set the offset prop to a number to change the tooltip position relative to the target element.
This way you can control the tooltip offset on the main axis only.
To control the offset on both axes, pass an object with mainAxis and crossAxis properties:
Arrow
Set the withArrow prop to add an arrow to the tooltip. The arrow is a div element rotated with transform: rotate(45deg).
The arrowPosition prop determines how the arrow is positioned relative to the target element when position is set to *-start and *-end values on the Popover component.
By default, the value is center – the arrow is positioned in the center of the target element if it is possible.
If you change arrowPosition to side, then the arrow will be positioned on the side of the target element,
and you will be able to control the arrow offset with the arrowOffset prop. Note that when arrowPosition is set to center,
the arrowOffset prop is ignored.
If you set arrowPosition to merge, the arrow will form a right triangle merged with the corresponding
corner of the tooltip, and the border radius of that corner will be removed. This mode only works
with *-start and *-end positions. Note that arrowOffset and arrowRadius props are ignored
when arrowPosition is set to merge.
Controlled
Change events
Events that trigger the tooltip can be changed with the events prop; it accepts an object
with the following properties that determine which events will trigger the tooltip:
hover– mouse hover event,trueby defaultfocus– focus/blur events excluding clicks on the target element,falseby defaulttouch– events for touchscreen devices,falseby default
import { Tooltip } from '@mantine/core';
function Demo() {
return (
<Tooltip
label="Tooltip"
events={{ hover: true, focus: true, touch: false }}
>
<button>target</button>
</Tooltip>
);
}
Interactive tooltip
By default, the tooltip closes as soon as the pointer leaves the target element, and the tooltip body ignores pointer events. Set the interactive prop to keep the tooltip open while the pointer travels from the target to the tooltip and rests over its content.
The interactive prop satisfies the hoverable condition of WCAG 2.1 success criterion 1.4.13: Content on Hover or Focus, so the pointer can reach the tooltip body without dismissing it, for example to read or select its content.
Do not put interactive or focusable content (links, buttons, inputs) inside a tooltip. Interactive content should be put in a Popover instead, which is reachable by mouse, keyboard, and touch.
Note that an interactive tooltip receives pointer events, which means that while it is open, it intercepts clicks and hover events of the elements that it overlaps. The tooltip stops receiving pointer events as soon as it starts closing. The interactive prop is not supported by Tooltip.Floating, which always follows the mouse.
Multiline
To enable multiline mode, set the multiline prop to enable line breaks and the w style prop to set the tooltip width:
Inline
Set the inline prop to use Tooltip with inline elements:
Change transition
Tooltip is built with the Transition component; it supports transitionProps props:
import { Button, Tooltip } from '@mantine/core';
function Demo() {
return (
<Tooltip
label="Tooltip with custom transition"
transitionProps={{ transition: 'skew-up', duration: 300 }}
>
<Button>Button with tooltip</Button>
</Tooltip>
);
}
All available premade transitions:
Close and open delay
You can delay tooltip open/close events by setting the openDelay and closeDelay props in ms:
Tooltip delay group
The Tooltip.Group component can be used to sync open and close delays for multiple tooltips:
Floating tooltip
Tooltip.Floating component has the same API as the Tooltip component but the tooltip will follow the mouse:
Accessibility
Tooltip follows the WAI-ARIA tooltip pattern:
- The tooltip body has
role="tooltip"attribute - The target element has
aria-describedbyattribute Tooltip.Floatingis ignored by screen readers- Uncontrolled tooltips are dismissed with
Escapewithout moving the pointer or focus
By default, Tooltip is not triggered by focus events and thus users who use a screen reader
or navigate with the keyboard will not be able to get tooltip content. Set the events prop to enable
focus/blur tooltip events:
import { Button, Tooltip } from '@mantine/core';
// Tooltip will be visible for screen readers
function Demo() {
return (
<Tooltip
label="Tooltip"
events={{ hover: true, focus: true, touch: false }}
>
<Button>Button with tooltip</Button>
</Tooltip>
);
}
WCAG 2.1 success criterion 1.4.13: Content on Hover or Focus
additionally requires content that appears on hover to be dismissable, hoverable and persistent.
Tooltip is persistent out of the box and dismissable if its opened state is not controlled
(Escape closes it without moving the pointer – if you control the opened prop, you are responsible
for handling Escape yourself). Tooltip is not hoverable by default – set the
interactive prop to make the tooltip body hoverable:
import { Button, Tooltip } from '@mantine/core';
// Tooltip stays open while the pointer is over its content
function Demo() {
return (
<Tooltip label="Tooltip" interactive>
<Button>Button with tooltip</Button>
</Tooltip>
);
}
源码参数参考
以下实现签名和类型从本地固定版本源码生成。保留可选属性、原生继承类型、联合分支和 never 限制;不会将其他设计系统的 API 混入。forwardRef 实现中的 ref 属于 React 引用,不是新增业务属性。此区域是原始类型参考,不是上游说明的全文翻译。
Tooltip(_props)
export interface TooltipProps extends TooltipBaseProps {
/** Called when tooltip position changes */
onPositionChange?: (position: FloatingPosition) => void;
/** Open delay in ms */
openDelay?: number;
/** Close delay in ms @default 0 */
closeDelay?: number;
/** Controlled opened state */
opened?: boolean;
/** Uncontrolled tooltip initial opened state */
defaultOpened?: boolean;
/** Space between target element and tooltip in px @default 5 */
offset?: number | FloatingAxesOffsets;
/** If set, the tooltip has an arrow @default false */
withArrow?: boolean;
/** Arrow size in px @default 4 */
arrowSize?: number;
/** Arrow offset in px @default 5 */
arrowOffset?: number;
/** Arrow `border-radius` in px @default 0 */
arrowRadius?: number;
/** Arrow position relative to the tooltip @default side */
arrowPosition?: ArrowPosition;
/** Props passed down to the `Transition` component that used to animate tooltip presence, use to configure duration and animation type @default { duration: 100, transition: 'fade' } */
transitionProps?: TransitionOverride;
/** Determines which events will be used to show tooltip @default { hover: true, focus: false, touch: false } */
events?: { hover: boolean; focus: boolean; touch: boolean };
/** If set, the tooltip stays open while the pointer is over it @default false */
interactive?: boolean;
/** Must be set if the tooltip target is an inline element */
inline?: boolean;
/** If set, the tooltip is not unmounted from the DOM when hidden, `display: none` styles are applied instead */
keepMounted?: boolean;
/** Changes floating ui [position strategy](https://floating-ui.com/docs/usefloating#strategy) @default 'absolute' */
floatingStrategy?: FloatingStrategy;
/** If set, adjusts text color based on background color for `filled` variant */
autoContrast?: boolean;
/** Selector, ref of an element or element itself that should be used for positioning */
target?: React.RefObject<HTMLElement | null> | HTMLElement | null | string;
/** If set, the tooltip is hidden when the target element is removed from the DOM, hidden with `display: none` or scrolled out of the visible area. Has no effect on `Tooltip.Floating` @default true */
hideDetached?: boolean;
}
export type TooltipFactory = Factory<{
props: TooltipProps;
ref: HTMLDivElement;
stylesNames: TooltipStylesNames;
vars: TooltipCssVariables;
staticComponents: {
Floating: typeof TooltipFloating;
Group: typeof TooltipGroup;
};
}>;
原生与外部类型
以下外部类型仍由 React 或资源自身依赖定义,没有手工展开为虚构属性。实际可用类型以安装版本的 TypeScript 检查为准。
Factory<{
props: TooltipProps;
ref: HTMLDivElement;
stylesNames: TooltipStylesNames;
vars: TooltipCssVariables;
staticComponents: {
Floating: typeof TooltipFloating;
Group: typeof TooltipGroup;
};
}>
TooltipBaseProps
FloatingPosition
FloatingAxesOffsets
ArrowPosition
TransitionOverride
FloatingStrategy
React.RefObject<HTMLElement | null>
HTMLElement
HTMLDivElement
TooltipStylesNames
TooltipCssVariables