react实现聊天窗口
React 实现聊天窗口的关键步骤
搭建基础组件结构
创建核心组件:ChatWindow(主容器)、MessageList(消息列表)、MessageInput(输入框)。使用函数式组件结合Hooks管理状态。
状态管理
通过useState维护消息列表和当前输入内容:
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState('');
消息渲染逻辑
在MessageList组件中映射消息数组,区分发送/接收样式:
{messages.map((msg, index) => (
<div key={index} className={msg.isSent ? 'sent' : 'received'}>
{msg.text}
</div>
))}
处理用户输入
为输入框绑定onChange和onSubmit事件:
const handleSend = () => {
if (inputValue.trim()) {
setMessages([...messages, { text: inputValue, isSent: true }]);
setInputValue('');
}
};
进阶功能实现
自动滚动到底部
使用useRef和useEffect实现消息更新后自动滚动:
const messagesEndRef = useRef(null);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
消息时间戳显示
扩展消息对象包含时间数据:
{
text: inputValue,
isSent: true,
timestamp: new Date().toLocaleTimeString()
}
支持多行输入
将<input>替换为<textarea>并添加样式控制:
textarea {
min-height: 40px;
max-height: 120px;
resize: none;
}
样式优化建议
响应式布局
使用CSS Grid或Flexbox确保窗口适应不同屏幕尺寸:
.chat-window {
display: flex;
flex-direction: column;
height: 100vh;
}
消息气泡样式
为发送/接收消息添加差异化样式:
.sent {
align-self: flex-end;
background-color: #0084ff;
color: white;
}
.received {
align-self: flex-start;
background-color: #f1f0f0;
}
动画效果
通过CSS Transition增强交互体验:
.message {
transition: all 0.3s ease;
opacity: 0;
transform: translateY(10px);
}
.message.show {
opacity: 1;
transform: translateY(0);
}






