【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 小时前
从“死了么”到“我在”:用uniCloud开发一款温暖人心的App
前端·uni-app
小徐_23331 小时前
uni-app 组件库 Wot UI 的 AI 友好型编程指南
前端·uni-app
HelloReader1 小时前
Flutter Widget 基础手把手教你创建自定义组件(二)
前端
Hilaku1 小时前
在 HTTP/3 普及的 2026 年,那些基于 Webpack 的性能优化经验,有一半该扔了
前端·javascript·面试
前端付豪1 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
HelloReader1 小时前
从零创建你的第一个 Flutter 应用(一)
前端
程序员阿峰1 小时前
别再写JS监听滚动了!一行CSS搞定导航固定+通讯录效果(附3个案例)
前端
进击的尘埃1 小时前
基于 LLM Function Calling 的前端动态表单生成引擎:从 JSON Schema 映射到运行时组件树的端到端实现
javascript
wordbaby1 小时前
前端进阶:小程序 Canvas 2D 终极指北 — 给图片优雅添加水印
前端·canvas
树上有只程序猿1 小时前
OpenClaw虽香,但不是人人都养得起“小龙虾
前端·openai