React+MUI聊天应用文本气泡适配换行文本问题
ReactJS/MUI聊天应用文本气泡宽度适配问题
开发基于ReactJS/MUI的聊天应用时遇到文本气泡尺寸适配问题:气泡采用Typography组件,已设置maxWidth: '65%'等样式属性。单行文本时气泡能适配内容宽度,但文本换行后气泡会直接占满65%的最大宽度,右侧出现多余空白。尝试过多种方案均无效,因对HTML/CSS不熟悉,无法将通用解决方案迁移到MUI场景中。
完整代码
import React from 'react'; import { Box, Typography, useTheme } from '@mui/material'; interface MessageComponentProps { text: string; fromUser: boolean; sendTime: Date; } export const MessageComponent: React.FC<MessageComponentProps> = ({ text, fromUser, sendTime }) => { const theme = useTheme(); const bubbleStyle = { bgcolor: fromUser ? theme.palette.primary.main : '#f1f1f1', color: fromUser ? 'white' : 'black', p: 1, borderRadius: '8px', maxWidth: '65%', wordBreak: 'break-word', display: 'inline-block', my: 0, fontFamily: 'Inter, sans-serif', fontWeight: '100', fontSize: '14px', }; const formattedTime = sendTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); return ( <Box sx={{ display: 'flex', justifyContent: fromUser ? 'flex-end' : 'flex-start', width: '100%', '&:hover .timestamp': { display: 'block', }, }} > {fromUser && ( // 己方消息,在左侧显示时间戳 <Typography variant="caption" sx={{ color: 'lightgrey', alignSelf: 'center', mr: 1, display: 'none' }} className="timestamp"> {formattedTime} </Typography> )} <Typography variant="body1" sx={bubbleStyle}> {text} </Typography> {!fromUser && ( // 对方消息,在右侧显示时间戳 <Typography variant="caption" sx={{ color: 'lightgrey', alignSelf: 'center', ml: 1, display: 'none' }} className="timestamp"> {formattedTime} </Typography> )} </Box> ); };
已尝试的方案
- 设置
width='fit-content':宽度超出65%限制,换行后仍有多余空白 - 使用隐藏div/span/Typography:未解决问题,还可能导致提前换行
- 使用ResizeObserver:无效果
- 嵌套MessageComponentText组件:无效
- JS动态测量文本宽度:无效果
内容的提问来源于stack exchange,提问作者mkamin
相关产品推荐
相关产品推荐

