React结合Tailwind实现多行文本截断与Read More按钮条件渲染
实现笔记内容超出三行显示「查看更多」按钮的方案
核心思路
结合Tailwind的line-clamp插件控制文本行数,用React状态管理展开/收起状态,同时通过DOM元素的高度对比判断内容是否超出三行,实现按钮的条件渲染。
具体实现步骤
确保Tailwind line-clamp插件启用
若未配置,在tailwind.config.js中添加插件:module.exports = { plugins: [ require('@tailwindcss/line-clamp'), ], }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
相关产品推荐
相关产品推荐

