Material UI v5:Dialog内二维Grid布局的字符串截断问题求助
在Material UI v5 Dialog的二维Grid布局中实现字符串截断
问题场景
我正在使用Material UI v5进行布局,需要在Dialog内的二维Grid布局中实现字符串截断,目标是创建一个文件上传组件(布局为:上方是可截断的文件名+右侧进度百分比,下方是进度条)。
我已经能实现一维Grid布局的字符串截断效果:文件名过长时会自动截断,右侧正常显示百分比。对应的代码如下:
export function App() { return ( <Dialog open={true} fullWidth maxWidth="xs"> <DialogContent> <Grid container columnSpacing={2}> <Grid item xs zeroMinWidth> <Typography noWrap> long filename which needs to be truncated long filename which needs to be truncated </Typography> </Grid> <Grid item xs="auto"> <Typography>100%</Typography> </Grid> </Grid> </DialogContent> </Dialog> ) }
但当添加LinearProgress指示器改成二维布局后,出现了内容溢出的问题(文件名部分超出Dialog范围),推测溢出长度恰好等于Typography组件的原始长度。当前代码如下:
export function App() { return ( <Dialog open={true} fullWidth maxWidth="xs"> <DialogContent> <Grid container direction="column"> <Grid item> <Grid container columnSpacing={2}> <Grid item xs zeroMinWidth> <Typography noWrap> long filename which needs to be truncated long filename which needs to be truncated </Typography> </Grid> <Grid item xs="auto"> <Typography>100%</Typography> </Grid> </Grid> </Grid> <Grid item> <LinearProgress/> </Grid> </Grid> </DialogContent> </Dialog> ) }
解决方法
问题根源是外层纵向Grid容器未被限制宽度,导致内部横向Grid可以超出Dialog的范围。只需做以下修改即可:
- 给外层纵向Grid容器添加宽度限制,确保它占满DialogContent的宽度;
- 给每个子Grid item设置
xs={12},让它们占满整行宽度,进一步约束内部布局。
修改后的完整代码:
export function App() { return ( <Dialog open={true} fullWidth maxWidth="xs"> <DialogContent> <Grid container direction="column" sx={{ width: '100%' }}> <Grid item xs={12}> <Grid container columnSpacing={2}> <Grid item xs zeroMinWidth> <Typography noWrap> long filename which needs to be truncated long filename which needs to be truncated </Typography> </Grid> <Grid item xs="auto"> <Typography>100%</Typography> </Grid> </Grid> </Grid> <Grid item xs={12}> <LinearProgress/> </Grid> </Grid> </DialogContent> </Dialog> ) }
或者也可以简化为仅给包裹横向Grid的Grid item添加宽度限制,效果相同:
// 修改包裹横向Grid的item <Grid item sx={{ width: '100%' }}> <Grid container columnSpacing={2}> {/* 原有代码 */} </Grid> </Grid>
内容的提问来源于stack exchange,提问作者julian.a
相关产品推荐
相关产品推荐

