本文介绍如何利用 `useref` 和 `scrollintoview` 在 react 应用中实现聊天消息列表的自动滚动,确保新消息添加后容器平滑滚动至底部,提升用户体验。
在构建实时聊天或对话式 UI(如 AI 助手界面)时,一个常见且关键的交互需求是:每当新消息被添加到消息列表末尾,容器应自动滚动到底部,使最新消息始终可见。React 本身不提供内置的滚动控制机制,但结合 useRef、useEffect 和原生 DOM 方法 scrollIntoView(),我们可以优雅、高效地实现这一功能。
import { useEffect, useRef, useState } from 'react';
function ChatBox() {
const [value, setValue] = useState('');
const [currentChat, setCurrentChat] = useState>([]);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// 每当 currentChat 更新,自动滚动到底部
useEffect(() => {
scrollToBottom();
}, [currentChat]);
const getMessages = () => {
if (!value.trim()) return;
// 模拟发送用
户消息 + 接收响应(此处应替换为实际 API 调用)
const newUserMsg = { role: 'user', content: value };
const newBotMsg = { role: 'assistant', content: `Echo: ${value}` };
setCurrentChat(prev => [...prev, newUserMsg, newBotMsg]);
setValue('');
};
return (
{/* 消息容器 */}
{currentChat.map((msg, index) => (
-
{msg.role}
{msg.content}
))}
{/* 滚动锚点:必须放在列表末尾 */}
{/* 输入区域 */}
setValue(e.target.value)}
placeholder="Type a message..."
style={{ padding: '8px', marginRight: '8px', width: '70%' }}
/>
);
}
export default ChatBox; 通过以上方式,你无需操作 scrollTop 或手动计算高度,即可实现简洁、可靠、符合 React 声明式思维的自动滚动逻辑。