如何为描述文本设置响应式宽度并实现自动换行(不使用TextField)
解决描述文本响应式换行问题
问题根源
你的代码里有两个核心问题导致文本无法换行:
- 内层Grid设置了固定宽度
width: 500,在小屏设备上会超出容器,同时限制了描述文本的可用空间 - 描述文本的
Typography组件没有配置强制换行的样式,遇到无空格的长连续字符时会横向溢出
解决方案(无需使用TextField)
直接调整布局和文本样式即可,以下是修改后的关键代码:
<Container maxWidth="lg"> <Grid container spacing={2}> <Grid item xs={12} md={4}> <Box sx={{height: {xs: 150, md: 300}, width: '300px', border:1, padding: '20px', borderRadius: '10px', display: {xs: 'flex'}}}> <Box component="img" sx={{height: '100%', width: '100%', objectFit: 'contain'}} src={singleProduct.img}/> </Box> </Grid> <Grid container item xs={12} md={8}> <Box sx={{display:'flex', flexDirection: 'column', margin:'auto', width: '100%'}}> {/* 新增width:100%确保占满父容器 */} <Typography variant="h5" sx={{fontWeight: 'bold', textTransform: 'uppercase'}}> {singleProduct.title}</Typography> <Box sx={{height: '40px', width: '100%', paddingY: '40px',paddingX: '20px', display:'flex', alignItems:'center', borderBottom: 1}}> <Typography variant='h3' sx={{color: '#00c853', fontWeight: 800}}> ₱ {singleProduct.price}.00</Typography> </Box> {/* 移除固定width:500,改用width:100%继承父容器宽度 */} <Grid sx={{width: '100%'}} container spacing={2} pt={4}> {/* 调整小屏布局为上下排列,避免横向拥挤 */} <Grid item xs={12} sm={4} sx={{lineHeight: 2}}> <Typography variant="body1" fontWeight={600} color="#757575">Seller: </Typography> <Typography variant="body1" fontWeight={600} color="#757575">StudentID: </Typography> <Typography variant="body1" fontWeight={600} color="#757575">Dept: </Typography> <Typography variant="body1" fontWeight={600} color="#757575">Desc: </Typography> </Grid> <Grid item xs={12} sm={8}> <Typography variant="body1" fontWeight={700} color="#212121">John Doe</Typography> <Typography variant="body1" fontWeight={700} color="#212121">{singleProduct.seller_id?.studentId}</Typography> <Typography variant="body1" fontWeight={700} color="#212121">{singleProduct.seller_id?.department}</Typography> {/* 添加换行样式,确保长文本/连续字符自动换行 */} <Typography variant="body1" fontWeight={700} color="#212121" sx={{ whiteSpace: 'normal', wordWrap: 'break-word', overflowWrap: 'break-word' }} >{singleProduct.description}</Typography> </Grid> </Grid> </Box> </Grid> </Grid> </Container>
关键修改点说明
- 移除固定宽度:把内层Grid的
width:500改成width:'100%',让它自适应父容器的宽度,保证响应式效果 - 优化小屏布局:将内层两个Grid的
xs=4/xs=8改成xs=12 sm=4/xs=12 sm=8,在手机等小屏设备上自动切换为上下排列,避免文本拥挤 - 强制文本换行:给描述文本的Typography添加
whiteSpace: 'normal'(确保文本不强制单行)、wordWrap: 'break-word'和overflowWrap: 'break-word'(处理无空格的长连续字符,比如长单词、URL)
内容的提问来源于stack exchange,提问作者Zurcemozz
相关产品推荐
相关产品推荐

