如何在React/CSS或Material UI中以行高的倍数截断文本



我在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;

不幸的是,您不能在多行上添加省略,它适用于单个水平行。

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

在你的代码中,你可以有

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>

最新更新