You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React结合Tailwind实现多行文本截断与Read More按钮条件渲染

实现笔记内容超出三行显示「查看更多」按钮的方案

核心思路

结合Tailwind的line-clamp插件控制文本行数,用React状态管理展开/收起状态,同时通过DOM元素的高度对比判断内容是否超出三行,实现按钮的条件渲染。

具体实现步骤

  1. 确保Tailwind line-clamp插件启用
    若未配置,在tailwind.config.js中添加插件:

    module.exports = {
      plugins: [
        require('@tailwindcss/line-clamp'),
      ],
    }
    
  2. React组件完整代码
    使用useState管理展开状态,useRef获取文本元素,useEffect判断内容是否超出:

    import { useState, useRef, useEffect } from 'react';
    
    function NoteItem({ note }) {
      const [isExpanded, setIsExpanded] = useState(false);
      const [isTruncated, setIsTruncated] = useState(false);
      const textRef = useRef(null);
    
      useEffect(() => {
        if (textRef.current) {
          // 对比内容总高度和可视高度,判断是否超出三行
          setIsTruncated(textRef.current.scrollHeight > textRef.current.clientHeight);
        }
      }, [note?.noteContent]);
    
      return (
        <div className="space-y-2">
          <p
            ref={textRef}
            className={`break-words text-xl ${isExpanded ? '' : 'line-clamp-3'}`}
          >
            {note?.noteContent}
          </p>
          {isTruncated && (
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="text-blue-500 hover:underline text-sm"
            >
              {isExpanded ? '收起' : '查看更多'}
            </button>
          )}
        </div>
      );
    }
    

关键细节说明

  • 高度判断逻辑:通过scrollHeight(元素内容总高度)和clientHeight(元素可视高度)的对比,比纯文本长度判断更准确,能适配不同字体、行高的情况。
  • 状态联动:isExpanded控制文本是否展开,isTruncated控制按钮是否显示,只有内容确实超出时才渲染按钮。
  • Tailwind类切换:收起时用line-clamp-3限制行数,展开时移除该类让文本完整显示。

内容的提问来源于stack exchange,提问作者trevinshu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:55:28