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

如何在React.js与Tailwind CSS中实现字符串截断,控制卡片标题显示行数

标题截断实现方案

原代码使用Tailwind CSS编写,以下为两种截断效果的对应实现:


1. 仅显示1行(超出显示省略号)

直接给标题标签添加Tailwind内置的truncate类即可,完整代码如下:

import React from 'react';

function SampleArticle({ color, title }) {
  return (
    <div>
      <div className='shadow-md p-4 m-2'>
        <div style={{ backgroundColor: color }} className='h-12 w-20'>
          <h2 className='text-gray-100 bg-textsecondary text-center justify-center truncate'>
            {title}
          </h2>
        </div>
      </div>
    </div>
  );
}

export default SampleArticle;

2. 最多显示2行(超出显示省略号)

使用Tailwind 3+内置的line-clamp-2类实现,完整代码如下:

import React from 'react';

function SampleArticle({ color, title }) {
  return (
    <div>
      <div className='shadow-md p-4 m-2'>
        <div style={{ backgroundColor: color }} className='h-12 w-20'>
          <h2 className='text-gray-100 bg-textsecondary text-center justify-center line-clamp-2'>
            {title}
          </h2>
        </div>
      </div>
    </div>
  );
}

提示:如果使用的Tailwind版本低于3.3,需要先安装@tailwindcss/line-clamp插件并在配置文件中引入,才可使用line-clamp系列类。


无Tailwind环境的原生实现方案

如果项目没有使用Tailwind,可自定义CSS类实现效果:

对应CSS规则

/* 单行截断 */
.text-truncate-1 {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* 两行截断 */
.text-truncate-2 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
}

组件中使用

给h2标签添加对应的类名即可:

<h2 className='text-gray-100 bg-textsecondary text-center justify-center text-truncate-1'>
  {title}
</h2>

按字符数截断方案(兼容极端场景)

如果需要按固定字符数截断而非按容器宽度截断,可使用JS工具函数实现:

import React from 'react';

// 截断工具函数,第二个参数可自定义最大字符数
const truncateText = (text, maxLength = 12) => {
  return text?.length > maxLength ? `${text.slice(0, maxLength)}...` : text;
}

function SampleArticle({ color, title }) {
  return (
    <div>
      <div className='shadow-md p-4 m-2'>
        <div style={{ backgroundColor: color }} className='h-12 w-20'>
          <h2 className='text-gray-100 bg-textsecondary text-center justify-center'>
            {truncateText(title, 12)}
          </h2>
        </div>
      </div>
    </div>
  );
}

export default SampleArticle;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:57:02