【问题标题】:How to truncate the text by multiples of the line height in React/CSS or Material UI? [duplicate]如何在 React/CSS 或 Material UI 中按行高的倍数截断文本? [复制]
【发布时间】:2021-03-15 13:46:09
【问题描述】:

我在 Material UI 中创建了一张包含文本的卡片。我想修复卡片的高度,如果超过 3 行,则将其中的文本截断。最好的方法是什么?

下面是我的代码,如您所见,我尝试使用 CSS 来执行此操作,但是 (a) 省略号不显示 (b) 溢出会在水平方向切掉文本,所以我会喜欢有办法通过线高的倍数而不是像素来做到这一点。如果显示器尺寸调整,我也希望它仍然可以工作。

import React from 'react';

// Material UI
import {
  Card,
  CardActionArea,
  CardContent,
  CardMedia,
  makeStyles,
  Typography,
} from '@material-ui/core';

const useStyles = makeStyles(theme => ({
  media: {
    height: 140,
  },
  title: {
    height: 50,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },  
  description: {
    height: 50,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },
}));

const ContentThumbnail = ({ image, title, description, date }) => {
  const classes = useStyles();
  return (
    <Card>
      <CardActionArea>
        <CardMedia
          image={image}
          title=""
          className={classes.media}
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2" className={classes.title}>
            {title}
          </Typography>
          <Typography variant="body2" component="p" className={classes.description}>
            {description}
          </Typography>
        </CardContent>
      </CardActionArea>
    </Card>
  );
};


export default ContentThumbnail;

【问题讨论】:

    标签: javascript css reactjs material-ui


    【解决方案1】:

    很遗憾,您不能在多行上添加省略号,它适用于每条水平线。

    一种解决方法是在显示省略号之前计算您可以拥有的符号总数。

    在您的代码中,您可以拥有

    const [description, setDescription] = useState('');
    const MAX_SYMBOLS_ALLOWED = 50;
    
    useEffect(() => {
      if(description.length >= MAX_SYMBOLS_ALLOWED) {
        // 3 is for the number of dots ( the elipsis )
        const transformed = description.substr(0, MAX_SYMBOLS_ALLOWED - 2);
    
        setDescription(`${transformed}...`)
      }
    
    }, [description])
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

    【讨论】:

    • 非常感谢 Tyhomira。如果我无法通过行高甚至 em(字符宽度)实现截断,这对我来说肯定是一个有用的选择。知道 CSS 仅适用于单行是很有用的。再次感谢你:)
    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2016-10-05
    • 2021-04-14
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多