【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>
  );
};
相关推荐
q***64974 分钟前
SpringSecurity踢出指定用户
android·前端·后端
q***76667 分钟前
SpringSecurity 实现token 认证
android·前端·后端
llxxyy卢8 分钟前
xss-maps(1-12)尝试思路过关加源码分析
前端·xss
Amy_yang10 分钟前
js 封装时间格式化,将单位有秒(s)的数据转换为'00:00:00'格式
javascript
interception11 分钟前
爬虫js逆向,jsdom补环境,抖音,a_bogus
javascript·爬虫·python
小璞12 分钟前
一、React Fiber 架构与任务调度详解
前端·react.js·前端框架
小璞12 分钟前
四、虚拟 DOM 与 Diff 算法:架构设计的智慧
前端·react.js·前端框架
南蓝13 分钟前
【AI 日记】调用大模型的时候如何按照 sse 格式输出
前端·人工智能
一树论15 分钟前
浏览器插件开发经验分享二:如何处理日期控件
前端·javascript
小璞15 分钟前
六、React 并发模式:让应用"感觉"更快的架构智慧
前端·react.js·架构