展示类

工具提示

工具提示用于对一个元素进行标识或者附上少量辅助信息,最典型的场景是向用户解释图标的含义、展示被截断的文本、显示图片的描述等。

代码演示

如何引入

import { Tooltip } from '@fibrous/semi-ui-react';

注意事项

Tooltip 通过 Fragment ref 直接找到 children 渲染出的 DOM 元素,用于计算弹出层位置并监听鼠标与焦点事件,因此 children 可以是 DOM 节点、函数组件或类组件,不需要透传 ref。

键盘操作(onKeyDown)、tabIndex 与 aria-* 属性以 props 的形式传给 children。children 是自定义组件时,需要把收到的 props 透传到底层的 DOM 元素上,否则触发器无法用键盘打开弹出层,读屏软件也读不到两者的关联。

Functional ComponentClassComponentDOM
代码
import React from 'react';
import { Tooltip, Space } from '@fibrous/semi-ui-react';

const style = { border: '2px solid var(--semi-color-border)', paddingLeft: 4, paddingRight: 4, borderRadius: 4 };

// Pass props to the underlying DOM and bind the ref (a plain prop in React 19)
function FCChildren({ ref, ...props }: React.ComponentProps<'span'>) {
    return (
        <span {...props} ref={ref} style={style}>
            Functional Component
        </span>
    );
}

// React 19 cannot reach a class component's DOM node, so wrap it in a real DOM node
class MyComponent extends React.Component {
    render() {
        return (
            <span {...this.props} style={style}>
                ClassComponent
            </span>
        );
    }
}

export default function TooltipDemo() {
    return (
        <Space>
            <Tooltip content="semi design">
                <FCChildren />
            </Tooltip>
            <Tooltip content="semi design">
                <span>
                    <MyComponent />
                </span>
            </Tooltip>
            <Tooltip content="semi design">
                <span style={style}>DOM</span>
            </Tooltip>
        </Space>
    );
}

位置

可以通过 position 配置弹出层方向以及对齐位置,position 详细可选值请参考下方 API 文档
配置为 top 时 向上弹出
配置为 topLeft 时,向上弹出,且弹出层与 children 左对齐(当arrowPointAtCenter=false时)
配置为 topRight 时,向上弹出,且弹出层与 children 右对齐(当arrowPointAtCenter=false时)
其他方向同理

TL
Top
TR
LT
Left
LB
RT
Right
RB
BL
Bottom
BR
代码
import { Tooltip, Tag, type TooltipPosition as Position } from '@fibrous/semi-ui-react';

export default function TooltipDemo() {
    const tops: [Position, string][] = [
        ['topLeft', 'TL'],
        ['top', 'Top'],
        ['topRight', 'TR'],
    ];
    const lefts: [Position, string][] = [
        ['leftTop', 'LT'],
        ['left', 'Left'],
        ['leftBottom', 'LB'],
    ];
    const rights: [Position, string][] = [
        ['rightTop', 'RT'],
        ['right', 'Right'],
        ['rightBottom', 'RB'],
    ];
    const bottoms: [Position, string][] = [
        ['bottomLeft', 'BL'],
        ['bottom', 'Bottom'],
        ['bottomRight', 'BR'],
    ];

    return (
        <div>
            <div style={{ marginLeft: 80, whiteSpace: 'nowrap' }}>
                {tops.map(([position, label], index) => (
                    <Tooltip
                        content={
                            <article>
                                <p>hi bytedance</p>
                                <p>hi bytedance</p>
                            </article>
                        }
                        arrowPointAtCenter={false}
                        position={position}
                        key={index}
                    >
                        <Tag style={{ margin: 8, padding: 20 }}>{label}</Tag>
                    </Tooltip>
                ))}
            </div>
            <div style={{ width: 80, float: 'left' }}>
                {lefts.map(([position, label], index) => (
                    <Tooltip
                        content={
                            <article>
                                <p>hi bytedance</p>
                                <p>hi bytedance</p>
                            </article>
                        }
                        arrowPointAtCenter={false}
                        position={position}
                        key={index}
                    >
                        <Tag style={{ margin: 8, padding: 20, width: 60 }}>{label}</Tag>
                    </Tooltip>
                ))}
            </div>
            <div style={{ width: 40, marginLeft: 300 }}>
                {rights.map(([position, label], index) => (
                    <Tooltip
                        content={
                            <article>
                                <p>hi bytedance</p>
                                <p>hi bytedance</p>
                            </article>
                        }
                        arrowPointAtCenter={false}
                        position={position}
                        key={index}
                    >
                        <Tag style={{ margin: 8, padding: 20, width: 60 }}>{label}</Tag>
                    </Tooltip>
                ))}
            </div>
            <div style={{ marginLeft: 80, clear: 'both', whiteSpace: 'nowrap' }}>
                {bottoms.map(([position, label], index) => (
                    <Tooltip
                        content={
                            <article>
                                <p>hi bytedance</p>
                                <p>hi bytedance</p>
                            </article>
                        }
                        arrowPointAtCenter={false}
                        position={position}
                        key={index}
                    >
                        <Tag style={{ margin: 8, padding: 20, width: 60 }}>{label}</Tag>
                    </Tooltip>
                ))}
            </div>
        </div>
    );
}

指向元素中心

默认情况下 arrowPointAtCenter=true,小三角始终指向 children 元素中心位置。你可以将其设置为 false,此时小三角将不再保持指向元素中心。弹出层与 children 边缘对齐

代码
import { Tooltip, Button } from '@fibrous/semi-ui-react';

export default function TooltipDemo() {
    return (
        <>
            <div>
                <Tooltip position="topLeft" content="semi design tooltip">
                    <Button type="secondary" style={{ marginRight: 8 }}>
                        指向元素中心
                    </Button>
                </Tooltip>
            </div>

            <div style={{ marginTop: 20 }}>
                <Tooltip content="semi design tooltip" arrowPointAtCenter={false} position="topLeft">
                    <Button type="secondary" style={{ marginRight: 8, width: 120 }}>
                        边缘对齐
                    </Button>
                </Tooltip>
            </div>
        </>
    );
}

触发时机

  • 配置触发展示的时机,默认为 hover,可选 hover/focus/click/custom/ 'contextMenu'
  • 设为 custom 时,需要配合 visible 属性使用,此时显示与否完全受控
  • contextMenu 为右键触发




代码
import { useState } from 'react';
import { Tooltip, Button, Input, RadioGroup, Radio } from '@fibrous/semi-ui-react';

export default function TooltipDemo() {
    const [visible, setVisible] = useState(false);

    return (
        <div>
            <Tooltip content="hi bytedance">
                <Button theme="solid" type="tertiary" style={{ marginBottom: 20 }}>
                    悬停显示
                </Button>
            </Tooltip>
            <br />
            <Tooltip content="hi bytedance" trigger="click">
                <Button style={{ marginBottom: 20 }}>点击显示</Button>
            </Tooltip>
            <br />
            <Tooltip content="hi bytedance" trigger="focus">
                <Input aria-label="聚焦显示" style={{ width: 100, marginBottom: 20 }} placeholder="聚焦显示" />
            </Tooltip>
            <br />
            <Tooltip content="hi bytedance" trigger="contextMenu">
                <Button theme="solid" type="secondary" style={{ marginBottom: 20 }}>
                    右键点击展示
                </Button>
            </Tooltip>
            <br />
            <Tooltip content="hi bytedance" trigger="custom" visible={visible}>
                <span style={{ display: 'inline-block' }}>
                    <RadioGroup type="button" onChange={(e) => setVisible(e.target.value)} value={visible}>
                        <Radio value>受控显示</Radio>
                        <Radio value={false}>受控隐藏</Radio>
                    </RadioGroup>
                </span>
            </Tooltip>
        </div>
    );
}

condition 条件触发

当 condition={false} 时,Tooltip 不响应 hover/click/focus 等触发行为(trigger='custom' 不受影响);condition 由 true 变为 false 时,已显示的弹出层立即关闭;visible 受控时只调用 onVisibleChange(false),使用方回写 visible 后才关闭。

condition
代码
import { useMemo, useState } from 'react';
import { Tooltip, Button, Switch, Space, Typography } from '@fibrous/semi-ui-react';

export default function TooltipDemo() {
    const [enabled, setEnabled] = useState(true);
    const content = useMemo(() => `condition is ${enabled ? 'true' : 'false'}`, [enabled]);

    return (
        <Space align="center">
            <Typography.Text id="tooltip-condition-label">condition</Typography.Text>
            <Switch aria-labelledby="tooltip-condition-label" checked={enabled} onChange={(v) => setEnabled(v)} />
            <Tooltip content={content} trigger="hover" condition={enabled}>
                <Button>Hover me</Button>
            </Tooltip>
            <Tooltip content={content} trigger="click" condition={enabled}>
                <Button>Click me</Button>
            </Tooltip>
        </Space>
    );
}

覆盖特定样式

你可以通过 className、style 为弹出层配置特定样式,例如覆盖默认的 maxWidth (240px)

Custom Style And ClassName
代码
import { Tooltip, Tag } from '@fibrous/semi-ui-react';

export default function TooltipDemo() {
    return (
        <div>
            <Tooltip
                style={{
                    maxWidth: 320,
                }}
                className="another-classname"
                content="hi semi semi semi semi semi semi semi"
            >
                <Tag style={{ marginRight: '8px' }}>Custom Style And ClassName</Tag>
            </Tooltip>
        </div>
    );
}

搭配 Popover 或 Popconfirm 使用

Tooltip、Popconfirm、Popover 的触发事件(mouseenter/mouseleave/click....)直接监听在触发元素的 DOM 上,直接嵌套时内外两层都能触发。
但外层注入的 aria-describedby、data-popupid 与方向键处理会被内层组件丢弃:读屏读不到外层的提示,键盘聚焦也打不开外层 hover 触发的弹出层。
需要这些能力时,在中间加一层元素(div 或 span)作为外层的触发元素。

代码
import { Tooltip, Popconfirm, Button } from '@fibrous/semi-ui-react';

export default function TooltipDemo() {
    return (
        <Popconfirm content="是否确认删除" title="确认" style={{ width: 320 }}>
            <span style={{ display: 'inline-block' }}>
                <Tooltip content="删除评价">
                    <Button type="danger">删除</Button>
                </Tooltip>
            </span>
        </Popconfirm>
    );
}

仅当内容宽度超出时展示 Tooltip

Semi 为这种场景提供了 Typography 组件,可以更简单快捷地满足需求。不需要自己再对 Tooltip 的出现做条件判断,详细的使用请参考Typography 组件文档

是一个很长很长很长很长5号标题

是一个很长很长很长很长的链接

多行截断,展示 Popover:Semi Design 是由抖音前端团队与 UED 团队共同设计开发并维护的设计系统。设计系统包含设计语言以及一整套可复用的前端组件,帮助设计师与开发者更容易地打造高质量的、用户体验一致的、符合设计规范的 Web 应用。

代码
import { Typography } from '@fibrous/semi-ui-react';

export default function TooltipDemo() {
    const { Paragraph, Title, Text } = Typography;

    return (
        <div>
            <Title heading={5} ellipsis={{ showTooltip: true }} style={{ width: 250 }}>
                是一个很长很长很长很长5号标题
            </Title>
            <br />
            <Text link ellipsis={{ showTooltip: true, pos: 'middle' }} style={{ width: 150 }}>
                是一个很长很长很长很长的链接
            </Text>
            <br />
            <br />
            <Paragraph ellipsis={{ rows: 3, showTooltip: { type: 'popover', opts: { style: { width: 300 } } } }} style={{ width: 300 }}>
                多行截断,展示 Popover:Semi Design 是由抖音前端团队与 UED 团队共同设计开发并维护的设计系统。设计系统包含设计语言以及一整套可复用的前端组件,帮助设计师与开发者更容易地打造高质量的、用户体验一致的、符合设计规范的 Web 应用。
            </Paragraph>
        </div>
    );
}

API 参考


Props

属性说明类型默认值
afterClose弹出层关闭且离场动画结束后调用。Type() => void-
afterOpen弹出层打开且进场动画结束后调用;没有进场动画时打开后即调用;进场结束前被关闭的打开不调用。Type() => void-
aria-label弹出层 role 为 dialog 时的 aria-label,其他 role 下忽略。string-
aria-labelledby弹出层 role 为 dialog 时的 aria-labelledby,其他 role 下忽略。string-
arrowPointAtCenter箭头是否指向触发元素中心,需要同时开启 showArrow。booleantrue
autoAdjustOverflow弹出层被遮挡时是否自动调整方向。booleantrue
children触发元素,应为真实 DOM 元素,或把 props 与 ref 透传到根 DOM 节点的函数式组件;文本等其他内容会被包进一个 span 作为触发元素。React.ReactNode-
className弹出层的样式名。string-
clickToHide点击弹出层及其内部任一元素时是否关闭弹出层。boolean-
clickTriggerToHide点击触发元素时是否关闭已打开的弹出层。boolean-
closeOnEsc弹出层打开期间按 Esc 是否关闭弹出层;trigger 为 custom 时只调用 onEscKeyDown,由使用方决定是否关闭。booleantrue
condition是否允许触发显示。仅显式设为 false 时,hover、click、focus 等触发行为不生效,trigger 为 custom 时仍按 visible 显示;由 true 变为 false 时立即关闭已显示的弹出层,visible 受控时只调用 onVisibleChange(false),使用方回写 visible 后才关闭。booleantrue
content弹出层内容,可以是节点,或返回节点的函数;函数的参数含 initialFocusRef,把它的 ref 绑到弹出层打开后需要获得焦点的元素上。React.ReactNode | RenderContent-
disableArrowKeyDown是否禁用在触发元素上按方向键把焦点移入弹出层。booleanfalse
disableFocusListenertrigger 为 hover 时,是否不响应键盘聚焦打开弹出层。booleanfalse
guardFocus焦点位于弹出层内时,Tab 是否在弹出层内循环。booleanfalse
keepDOM关闭时是否保留弹出层内容而不销毁。booleanfalse
motion是否展示弹出层动画。booleantrue
mouseEnterDelay指针移入后延迟显示的毫秒数,仅 trigger 为 hover 或 focus 时生效。number50
mouseLeaveDelay指针移出后延迟隐藏的毫秒数,仅 trigger 为 hover 或 focus 时生效,不小于 mouseEnterDelay。number50
onClickOutSide弹出层打开时,在触发元素与弹出层以外的区域按下鼠标时调用,参数为原生 MouseEvent;仅 trigger 为 click、contextMenu、custom 或开启 clickTriggerToHide 时有效。Type(e: MouseEvent) => void-
onEscKeyDowncloseOnEsc 为 true 时,弹出层打开期间按 Esc 调用,参数为原生 KeyboardEvent。Type(e: KeyboardEvent) => void-
onOpen弹出层显示、进场动画开始时调用,每次打开一次,早于 afterOpen,受控与非受控相同;悬停打开后指针已离开而撤回的打开不调用。Type() => void-
onVisibleChange弹出层显示状态变化时调用,参数为是否显示;visible 受控时只报告用户交互发起的请求,使用方自己改变 visible 不调用。Type(visible: boolean) => void-
position弹出层相对触发元素的位置,可选 top、topLeft、topRight、left、leftTop、leftBottom、right、rightTop、rightBottom、bottom、bottomLeft、bottomRight。Position"top"
prefixCls弹出层 wrapper 的类名前缀,设置后弹出层不再带 Tooltip 的样式。string"semi-tooltip"
preventScroll弹出层打开后聚焦 initialFocusRef 指向的元素时,是否阻止浏览器滚动到该元素。boolean-
ref组件的句柄,可调用下方 Methods 中的方法。TypeReact.Ref<TooltipHandle>-
returnFocusOnClose弹出层关闭后焦点是否回到触发元素,trigger 为 custom 时不生效。booleanfalse
role弹出层的 ARIA role。string"tooltip"
showArrow是否显示箭头三角形,也可以传入节点作为自定义箭头。boolean | React.ReactNodetrue
spacing弹出层与触发元素的距离,单位为像素;对象形式分别设置水平与垂直方向。number | { x: number; y: number }8
stopPropagation是否阻止弹出层上的 click、mousedown 与焦点进出事件冒泡。boolean-
style弹出层的内联样式;箭头颜色只读取对象形式中的 background-color。React.CSSProperties-
trigger触发显示的时机,可选 hover、focus、click、contextMenu 或 custom;custom 时显示与否完全由 visible 决定。Trigger"hover"
visible弹出层是否显示(受控)。传入后触发器、点击外部与 Esc 只通过 onVisibleChange 请求打开或关闭,使用方回写后才生效。boolean-
wrapperClassName触发元素需要被 span 包裹时,该 span 的类名。string-
wrapperId弹出层节点的 id,触发元素的 aria 属性指向它;缺省时自动生成。string-
wrapWhenSpecial触发元素禁用或加载中时,是否在外层包裹 span 以保证触发行为。booleantrue

Methods

方法说明类型
focusTrigger让触发元素获得焦点,仅在 returnFocusOnClose 为 true 且 trigger 不是 custom 时生效。Type() => void
getPopupId返回弹出层的 id。Type() => string
hide立即关闭弹出层,不移动焦点,并调用 onVisibleChange(false);visible 受控时只调用 onVisibleChange(false),使用方回写后才关闭。Type() => void
rePosition按触发器当前位置立即重新计算弹出层位置。弹出层已随滚动、窗口尺寸变化、触发器移动以及触发器或弹出层的尺寸变化自动重新定位,一般无需调用;跟随触发器移动会晚一帧,需要同一帧内对齐时调用。Type() => void

Tooltip 没有根 DOM 元素,未声明的属性不会透传到弹出层,className、style 落在弹出层上;触发元素保留自己的属性,并由 Tooltip 加上触发属性(如 aria-describedby、data-popupid、tabIndex)。

Accessibility

ARIA

  • Tooltip 具有 tooltip role,遵循 WAI-ARIA 规范中对于 Tooltip 的定义
  • Tooltip 的 content 与 children
    • 关于 content
      • content 的 wrapper 会被自动添加 id 属性,用于与 children 的 aria-describedby 匹配,关联 content 与 children
    • 关于 children
      • Tooltip 的内容(content)与其触发器(children)之间应当具有显式联系。Tooltip 会自动为 children 元素添加 aria-describedby 属性,值为 content wraper的 id
      • 若你 Tooltip的children 是Icon,不包含可见文本,我们推荐你在 children 上添加 aria-label 属性进行相应描述
// 推荐做法:给 Tooltip 的 children 添加 aria-label 描述
/* eslint-disable */
<Tooltip content={<p id="description">Edit your setting</p>}>
    <IconSetting aria-label="Settings"></IconSetting>
</Tooltip>

文案规范

  • 只展示信息说明和引导,不展示报错信息
  • 不在 tooltip 里只能是额外的链接和按钮
  • 尽量精简至一句话进行说明,不展示标点符号

设计变量

下表是组件内部的 Sass 变量,不能覆写。定制样式请覆写 --semi-* CSS 变量(见 Design Token 页),或写不分层的 CSS 规则。
Sass 变量值用法
$animation_duration-tooltip_out100mstooltip-显示及收起动画-动画持续时间
$animation_function-tooltip_outcubic-bezier(0.215, 0.61, 0.355, 1)tooltip-显示及收起动画-动画插值函数
$horizontal-rate0.24水平方向矫正因子
$vertical-rate0垂直方向矫正因子
$motion-zoom_scale-from0.8进出场动画的初始缩放
$color-tooltip-bg-defaultvar(--semi-grey-7)工具提示默认背景色
$color-tooltip-text-defaultvar(--semi-color-bg-0)工具提示默认文字颜色
$color-tooltip-icon-defaultvar(--semi-grey-7)工具提示默认图标颜色
$color-tooltip_arrow-icon-default$color-tooltip-icon-default工具提示默认小三角箭头颜色
$radius-tooltipvar(--semi-border-radius-medium)工具提示默认圆角
$spacing-tooltip_content-paddingLeft$spacing-base-tight工具提示内容左侧内边距
$spacing-tooltip_content-paddingRight$spacing-base-tight工具提示内容右侧内边距
$spacing-tooltip_content-paddingTop$spacing-tight工具提示内容顶部内边距
$spacing-tooltip_content-paddingBottom$spacing-tight工具提示内容底部内边距
$font-tooltip-fontSize$font-size-regular工具提示文本字号
$width-tooltip240px工具提示宽度 - 默认
$width-tooltip_arrow24px工具提示小三角箭头宽度 - 水平
$height-tooltip_arrow7px工具提示小三角箭头高度 - 水平
$height-tooltip_arrow_vertical24px工具提示小三角箭头高度 - 垂直
$width-tooltip_arrow_vertical7px工具提示小三角箭头宽度度 - 垂直
$spacing-tooltip_arrow_offset-x1px水平方向渲染会有缝隙,所以加个偏移量
$spacing-tooltip_arrow_offset-y1px垂直方向渲染会有缝隙,所以加个偏移量
$spacing-tooltip_arrow_adjusted_offset-y6px垂直方向上的校正偏移量,主要修正三角形有棱角的问题
$spacing-tooltip_arrow_adjusted_offset-xmath.round($horizontal-rate * $width-tooltip_arrow)水平方向上的校正偏移量,主要修正三角形有棱角的问题
$filter-tooltip-bgnone

FAQ

  • 为什么 Tooltip content 配置很长很长的内容时,某些情况下内容会超出显示区域?
    Tooltip 的弹出层设置了 overflow-wrap 为 break-word,过长的单词会断开换行。不同语言内容(纯英文、中文、中英文混合、其他语种混合)对换行的需求不一致,默认设置不符合预期时,可以通过 style/className(Vue 为 style/class)设置换行相关 CSS 属性进行调整。