You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅在文本触发ellipsis时显示Chakra UI的Tooltip组件?

实现Chakra UI Tooltip仅在文本溢出时显示

你当前的问题是Tooltip会无条件显示,我们需要改成仅当文本触发省略号(溢出容器)时才弹出Tooltip。核心思路是通过判断文本元素的实际宽度是否超过可视宽度,来控制Tooltip的显示状态。

直接上可行的实现方案:

自定义复用组件实现逻辑

封装一个组件,借助DOM元素的尺寸属性判断溢出状态,再结合Chakra UI的Tooltip属性控制显示:

import { Tooltip, Text } from '@chakra-ui/react';
import { useRef, useState, useEffect } from 'react';

const EllipsisTooltipText = ({ content }) => {
  const textRef = useRef(null);
  const [isTextOverflowed, setIsTextOverflowed] = useState(false);

  // 检测文本是否溢出的函数
  const checkOverflow = () => {
    if (!textRef.current) return;
    setIsTextOverflowed(textRef.current.scrollWidth > textRef.current.clientWidth);
  };

  useEffect(() => {
    // 初始化时检测一次
    checkOverflow();
    // 监听窗口大小变化,避免缩放后状态不更新
    window.addEventListener('resize', checkOverflow);
    // 组件卸载时移除监听
    return () => window.removeEventListener('resize', checkOverflow);
  }, [content]);

  return (
    <Tooltip label={content} isOpen={isTextOverflowed}>
      <Text
        ref={textRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {content}
      </Text>
    </Tooltip>
  );
};

// 使用示例
// <EllipsisTooltipText content="this is an example for a long text" />

关键逻辑说明

  • 用useRef获取Text组件对应的DOM节点,读取元素的实际宽度(scrollWidth)和可视宽度(clientWidth)
  • 当scrollWidth > clientWidth时,说明文本内容超出容器宽度触发了省略号,此时将isTextOverflowed设为true
  • 通过Tooltip的isOpen属性绑定该状态,仅在溢出时显示Tooltip
  • 监听窗口resize事件是为了适配窗口缩放场景,确保溢出状态能实时更新

如果需要支持多行溢出,只需把判断条件改成scrollHeight > clientHeight,同时调整Text的样式(比如设置lineClamp)即可。

内容的提问来源于stack exchange,提问作者wael zobani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 04:12:48