diff --git a/app/danmu/danmu.tsx b/app/danmu/danmu.tsx index ce692d5..8eed021 100644 --- a/app/danmu/danmu.tsx +++ b/app/danmu/danmu.tsx @@ -1,5 +1,5 @@ "use client"; -import { useState, useEffect, useCallback } from "react"; +import { useState, useEffect, useCallback, useRef } from "react"; import useWebSocket, { ReadyState } from "react-use-websocket"; import MessageDispatcher from "./message"; import { Token } from "@/lib/types"; @@ -8,6 +8,7 @@ const MOMO_IM_URL = "wss://live-ws.immomo.com/ws/im"; export const Danmu: React.FC<{ token: Token }> = ({ token }) => { const [messageHistory, setMessageHistory] = useState[]>([]); + const ref = useRef(null); const { sendMessage, lastMessage, readyState } = useWebSocket(MOMO_IM_URL, { heartbeat: { @@ -57,12 +58,17 @@ export const Danmu: React.FC<{ token: Token }> = ({ token }) => { } console.log(message); setMessageHistory((prev) => prev.concat(message)); + if (ref.current) { + setTimeout(() => { + ref.current.scrollTop = ref.current.scrollHeight; + }, 0); + } } } }, [lastMessage]); return ( -
+
{messageHistory.map((message, idx) => ( ))}