【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>
  );
};
相关推荐
全栈项目管理程序猿4 分钟前
Cesium-1.143 中文版 API
javascript·cesium
喜欢打篮球的普通人8 分钟前
LLVM后端指令选择
android·java·javascript
踩蚂蚁11 分钟前
在 ESP32 上跑自定义唤醒词:从 TFLite 到离线语音唤醒,一个下午搞定
前端
hunterandroid14 分钟前
Room 数据库迁移:让本地数据升级更稳
android·前端
徐小夕15 分钟前
倒腾2天,我开源了一款AI驱动的实时 3D CAD / 参数化建模工作台
前端·架构·github
少年白马醉春风丶20 分钟前
任务分解的经典范式 · 和 ReAct「走一步看一步」到底差在哪
前端
是烨笙啊20 分钟前
从 npm 与 Bun 的选择看 AI 时代的“最佳实践”焦虑
前端·人工智能·npm
lichenyang45324 分钟前
从 Web 容器到本地 HAR:我做了一个 HarmonyOS JSBridge 运行时框架 Demo
前端
超神熊猫26 分钟前
🧀🧀🧀前端仔如何快速上手python
前端·python
阿黎梨梨30 分钟前
AI 推理太慢用户要退钱?前端流式输出(Stream)究竟是何方神圣?
前端·vue.js