【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>
  );
};
相关推荐
Slice_cy14 分钟前
Mint 自研框架设计与实现:从重复开发走向配置驱动(二)
前端·后端·架构
greenbbLV17 分钟前
积分兑换商城供应商挑选:避坑要点与靠谱选择解析
前端·小程序
张元清26 分钟前
React useDropZone Hook:搭建一个文件拖放区(2026)
javascript·react.js
a11177633 分钟前
3D 建筑编辑器 Pascal Editor THreeJS 开源
前端·3d·html
jason_yang35 分钟前
写给女儿的英语App
前端·人工智能
思码梁田43 分钟前
CSS 定位详解:从相对到固定,掌握网页布局的核心
前端·javascript·css
勇往直前plus1 小时前
Vite :从双击 HTML 到现代前端开发
前端·html
muddjsv1 小时前
CSS 高级选择器精讲:伪类、伪元素、逻辑伪类与选择器解耦规范
前端·css
HH‘HH1 小时前
前端应用的离线暂停更新策略:原理、实现与最佳实践
开发语言·前端·php
软件开发技术深度爱好者1 小时前
HTML5实现数学函数画图器
前端·javascript·html5