【React 轮子】文本溢出后显示展开/收起按钮


javascript 复制代码
/** hooks
 * 用于文本展示时判断是否展示 展开/收起按钮 (包含监听 文本变化/页面尺寸变换)
 * @param { string } text 需要展示的文本
 * @param { number } maxLength 文本最大展示行数
 * @param { number } lineHeight 文本行高 (单位 px)
*/ 
import React, { useEffect, useRef, useState } from 'react';
export const TruncatedText = ({ text,lineHeight,maxLength }) => {
	// 用于判断目前展开与否
  const [isTruncated, setIsTruncated] = useState(true);
  //是否需要显示 展开收起按钮
  const [shouldShowMore, setShouldShowMore] = useState(false);
  
  const containerRef = useRef(null);

  useEffect(() => {
      const checkTruncation = () => {
          if (containerRef.current) {
            const { scrollHeight } = containerRef.current;
              setShouldShowMore(scrollHeight > lineHeight*maxLength);
          }
      }; 
      checkTruncation(); // 初次检查
    	// 监听页面缩放
      const resizeObserver = new ResizeObserver(checkTruncation);
      if (containerRef.current) {
          resizeObserver.observe(containerRef.current);
      }

      return () => {
          if (containerRef.current) {
              resizeObserver.unobserve(containerRef.current);
          }
      };
  }, [text]);

  const toggleTruncate = () => {
      setIsTruncated((prev) => !prev);
  };
 
  return (
    <div
      style={{
        position: 'relative',
        display: '-webkit-box',
        overflow: 'hidden',
        maxHeight: isTruncated ? `calc(${lineHeight}px * ${maxLength})` : 'none',
        transition: 'max-height 0.2s ease',
        fontSize: '14px',
        lineHeight: `${lineHeight}px`,
      }}
    >
      <span ref={containerRef} style={{display:'inline-block'}} >
        {text}
      </span>
      {shouldShowMore && (
          <a
            onClick={toggleTruncate}
            style={{
              background: '#fff',
              position: 'absolute',
              bottom: 0,
              right: 0,
            }}
          >
              {isTruncated ? ' -展开' : '收起'}
          </a>
      )}
    </div>
  );
};
相关推荐
爱勇宝1 分钟前
研究数字孪生的这半年,做了个 Demo,也有了一些新想法
前端·程序员
不可能片场18 分钟前
工程实践 一个缓存把选片从十分钟压到一分钟
前端·electron
前端小万19 分钟前
探索副业五个月,最终以放弃告终
前端·后端·面试
FRing0325 分钟前
JavaScript入门到精通二十四(正则表达式、元字符、修饰符)
开发语言·前端·javascript·正则表达式
葡萄城技术团队1 小时前
在 SpreadJS 里新增右键菜单,把业务动作放到用户手边
前端
大明二代1 小时前
从 RAG 到有记忆的 Agent:Mastra Memory 与 PostgreSQL 实战
前端·javascript·人工智能
deli0071 小时前
代码截图一键出 PNG 实测:3 种窗口风格,长行超 95 字符会被裁
前端
大哥43091 小时前
慢 ≠ 挂:AI 搜索降级判定的设计,与一次 reasoning 模型排查复盘
前端
UaoN1 小时前
作为全栈开发者,为什么看到 Shopify 回归原生,我依然选择 React Native
前端·后端
PBitW2 小时前
行内编辑,前端如何兜底?😭😭😭
前端·面试