本文介绍如何使用 react 的 `useref` 和 `scrollintoview` 实现消息列表新增时自动滚动到底部,确保最新消息始终可见,无需用户手动拖动滚动条。
在构建实时聊天界面时,一个关键的用户体验细节是:每当新消息(无论是用户输入还是服务端响应)被添加到消息列表中,容器应自动滚动至底部,使最新消息立即可见。React 本身不提供内置的滚动控制,但结合 useRef 和原生 DOM 方法,我们可以优雅、高效地实现这一功能。
import { useEffect, useRef, useState } from 'react';
// 假设这是你的组件主体
function ChatBox() {
const [value, setValue] = useState('');
const [currentChat, setCurrentChat] = useState>([]);
const [currentTitle, setCurrentTitle] = useState(null);
const [message, setMessage] = useState<{ content: string } | null>(null);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// 监听 currentChat 变化,自动滚动
useEffect(() => {
scrollToBottom();
}, [currentChat]);
// 模拟发送逻辑(请按实际业务替换)
const getMessages = () => {
if (!value.trim()) return;
const newAuthMsg = { role: 'auth', content: value };
const newResponseMsg = { role: 'message:', content: message?.content || 'Hello! How can I help?' };
setCurrentChat(prev => [...prev, newAuthMsg, newResponseMsg]);
setValue('');
};
return (
{/* 消息容器 —— 注意:必须设置固定高度 + overflow-y */}
{currentChat.map((chatMessage, index) =>
(
-
{chatMessage.role}
{chatMessage.content}
))}
{/* 关键:滚动锚点,置于列表末尾 */}
{/* 输入区域 */}
setValue(e.target.value)}
placeholder="Type a message..."
style={{ padding: '8px 12px', width: '70%' }}
/>
);
}
export default ChatBox; 通过 useRef 获取 DOM 节点 + scrollIntoView + 精准的 useEffect 依赖控制,即可零第三方库实现可靠、流畅的自动滚动。该方案轻量、可预测、易于维护,是 React 聊天应用中的推荐实践。