【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>
  );
};
相关推荐
哈哈你是真的厉害11 分钟前
基础入门 React Native 鸿蒙跨平台开发:ActionSheet 动作面板
react native·react.js·harmonyos
符文师19 分钟前
css3 新特性
前端·css3
ct97841 分钟前
WebGL开发
前端·gis·webgl
C_心欲无痕1 小时前
前端页面渲染方式:CSR、SSR、SSG
前端
果粒蹬i1 小时前
生成式 AI 质量控制:幻觉抑制与 RLHF 对齐技术详解
前端·人工智能·easyui
筱歌儿1 小时前
TinyMCE-----word表格图片进阶版
开发语言·javascript·word
弓.长.2 小时前
基础入门 React Native 鸿蒙跨平台开发:Transform 变换
react native·react.js·harmonyos
Ama_tor2 小时前
obsidian进阶の插件系列|Templater从小白到菜鸟
javascript·markdown·插件·obsidian
哈哈你是真的厉害2 小时前
基础入门 React Native 鸿蒙跨平台开发:ActivityIndicator 实现多种加载指示器
react native·react.js·harmonyos
WordPress学习笔记2 小时前
解决Bootstrap下拉菜单一级链接无法点击的问题
前端·bootstrap·html