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

React中使用MUI Typography实现按行数限制文本并添加省略号

按行数限制文本并添加末尾省略号(React + MUI Typography)

直接利用MUI Typography结合CSS原生行截断特性就能实现你要的效果,不需要手动计算字符数,完美避免单词中间截断的问题:

基础实现方案(MUI v5)

方法1:使用内置lineClamp属性(MUI v5.10+)

MUI从v5.10版本开始给Typography组件提供了lineClamp快捷属性,直接设置行数即可:

import Typography from '@mui/material/Typography';

const YourComponent = () => {
  const longText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been...";
  
  return (
    <Typography lineClamp={2}>
      {longText}
    </Typography>
  );
};

方法2:手动配置CSS属性(兼容所有MUI v5版本)

如果你的MUI版本低于v5.10,直接通过sx属性配置webkit行截断样式:

import Typography from '@mui/material/Typography';

const YourComponent = () => {
  const longText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been...";
  
  return (
    <Typography
      sx={{
        display: '-webkit-box',
        WebkitLineClamp: 2, // 限制行数
        WebkitBoxOrient: 'vertical',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        width: '100%', // 确保容器有固定宽度,否则截断可能不生效
      }}
    >
      {longText}
    </Typography>
  );
};

方案说明

  • 这两种方式都是基于CSS的行截断逻辑,会自动在最后一行的末尾添加省略号,不会像字符计数那样在单词中间截断,完全符合你要的效果。
  • 无需手动处理文本内容,适配不同字体、字号和容器宽度,自动处理换行逻辑。
  • 注意:容器需要有明确的宽度(比如设置width: 100%或固定像素值),否则line-clamp特性可能无法正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:49:55