Material UI 列表、ListItemText 中没有 WRAP 挑战

Che*_*ven 5 css material-ui

有没有办法不让文本换行ListItemText

在此输入图像描述

我需要 ListItemText 只是为了剪切单词而不需要任何扩展或滚动。

谢谢

小智 8

从 Material UI 版本 5.0.6 开始,您可以覆盖ListItemTextusingprimaryTypography属性。

有关ListItemText Api 文档的更多信息

PrimaryTypographyProps:这些道具将被转发到主要版式组件(只要disableTypography不为true)。

这意味着传递的 props 将被传递给Typography 组件

要隐藏或换行文本,我们可以限制 ListItem 的宽度(如果需要,取决于父项),在本例中将 设为maxWidth300px,然后使用primaryTypographyProps并传递一个style将具有whiteSpaceoverflowtextOverflow设置为隐藏的对象。

import { ListItem, ListItemText } from '@mui/material';

<ListItem
    sx={{
        maxWidth: 300
    }}
>
    <ListItemText
        primary={"Super long string that needs to be wrapped"}
        secondary={"other text not important"}
        primaryTypographyProps={{ 
            variant: 'subtitle2', 
            style: {
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
            }
        }
        secondaryTypographyProps={{ variant: 'caption' }}
    />
</ListItem>
Run Code Online (Sandbox Code Playgroud)

为了获得更多控制,您还可以禁用 Typography 并传递您自己的组件,该组件完全具有自己的样式(如果您愿意)。

disableTypography:如果为 true,则子项不会被 Typography 组件包裹。这对于通过使用 Typography 组件包装子(或主要)文本和可选的辅助文本来呈现替代 Typography 变体非常有用。