react实现聊天气泡
React 实现聊天气泡的方法
基础布局与样式
使用 CSS Flexbox 或 Grid 布局构建气泡容器。发送方和接收方气泡通常采用不同的背景色和对齐方式(右对齐/左对齐)。示例 CSS:
.bubble {
max-width: 70%;
padding: 10px 15px;
border-radius: 18px;
margin: 5px 0;
}
.sent {
align-self: flex-end;
background-color: #0084ff;
color: white;
}
.received {
align-self: flex-start;
background-color: #e5e5ea;
color: black;
}
动态消息渲染
通过 map 方法遍历消息数组,根据消息类型(发送/接收)应用不同样式类:
{messages.map((msg) => (
<div
key={msg.id}
className={`bubble ${msg.isSent ? 'sent' : 'received'}`}
>
{msg.text}
</div>
))}
时间戳显示
在气泡底部添加相对时间格式化显示:
<div className="timestamp">
{new Date(msg.timestamp).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
</div>
配套 CSS:

.timestamp {
font-size: 0.7em;
opacity: 0.8;
margin-top: 3px;
}
头像集成
使用 Avatar 组件与气泡组合布局:
<div className="message-container">
{!msg.isSent && <Avatar src={msg.avatar} />}
<div className={`bubble ${msg.isSent ? 'sent' : 'received'}`}>
{msg.text}
</div>
</div>
配套 CSS:

.message-container {
display: flex;
align-items: flex-end;
gap: 8px;
}
高级功能实现
消息状态指示器:添加已读/未读状态图标
{msg.isSent && (
<span className="status-icon">
{msg.read ? <ReadIcon /> : <UnreadIcon />}
</span>
)
动画效果:使用 CSS transitions 或 Framer Motion
.bubble {
transition: transform 0.2s, opacity 0.2s;
}
.new-message {
transform: scale(0.9);
opacity: 0;
animation: popIn 0.3s forwards;
}
@keyframes popIn {
to {
transform: scale(1);
opacity: 1;
}
}
响应式优化
通过媒体查询调整气泡最大宽度:
@media (max-width: 768px) {
.bubble {
max-width: 85%;
}
}
完整组件示例
function ChatBubble({ messages }) {
return (
<div className="chat-container">
{messages.map((msg) => (
<div
key={msg.id}
className={`message-container ${msg.isSent ? 'sent' : ''}`}
>
{!msg.isSent && <Avatar src={msg.avatar} />}
<div className={`bubble ${msg.isSent ? 'sent' : 'received'}`}>
<div className="text">{msg.text}</div>
<div className="timestamp">
{formatTime(msg.timestamp)}
{msg.isSent && <StatusIcon read={msg.read} />}
</div>
</div>
</div>
))}
</div>
);
}






