发布于 2026-01-06 0 阅读
0

一行代码即可实现聊天应用的自动滚动 + React Hook

一行代码即可实现聊天应用的自动滚动 + React Hook

在使用 WhatsApp、Twitch 或任何社交媒体应用时,当有新消息发送/接收时,聊天信息流会自动滚动到底部。在开发带有聊天功能的应用时,这绝对是一个应该包含的重要功能。

如果你不明白我在说什么,可以试试我做的这个小演示。输入一条消息并按下回车键,发送新消息时,消息会暂时消失在屏幕上,你需要滚动页面才能看到它。

如果你想亲自体验这个互动演示,请前往我的原始博客文章

聊天前

其实解决这个问题很简单,首先我们需要知道包裹所有聊天窗口的容器元素。然后选择该元素,获取其高度,scrollHeight再设置该元素的垂直滚动高度scrollTop

就是这样。



const el = document.getElementById('chat-feed');
// id of the chat container ---------- ^^^
if (el) {
  el.scrollTop = el.scrollHeight;
}


Enter fullscreen mode Exit fullscreen mode

这是添加了这项功能的新演示版本。现在,当有新消息到达时,页面会自动滚动到底部。

聊天后

现在来说说 React 的实现,我们将使用useRef&useEffect来访问元素并处理副作用。

这将接受dep一个参数作为依赖项,useEffect并返回一个ref我们将传递给聊天容器元素的元素。



import React from 'react'

function useChatScroll<T>(dep: T): React.MutableRefObject<HTMLDivElement> {
  const ref = React.useRef<HTMLDivElement>();
  React.useEffect(() => {
    if (ref.current) {
      ref.current.scrollTop = ref.current.scrollHeight;
    }
  }, [dep]);
  return ref;
}


Enter fullscreen mode Exit fullscreen mode

上述钩子的用法:



const Chat = () => {
  const [messages , setMessages] = React.useState([])
  const ref = useChatScroll(messages)
  return(
    <div ref={ref} >
      {/* Chat feed here */}
    </div>
  )
}


Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/deepcodes/automatic-scrolling-for-chat-app-in-1-line-of-code-react-hook-3lm1