feat: 自动滚动

This commit is contained in:
sealday 2024-04-07 02:02:08 +08:00
parent 25b7dd0f82
commit d723fc6cda

View File

@ -1,5 +1,5 @@
"use client"; "use client";
import { useState, useEffect, useCallback } from "react"; import { useState, useEffect, useCallback, useRef } from "react";
import useWebSocket, { ReadyState } from "react-use-websocket"; import useWebSocket, { ReadyState } from "react-use-websocket";
import MessageDispatcher from "./message"; import MessageDispatcher from "./message";
import { Token } from "@/lib/types"; 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 }) => { export const Danmu: React.FC<{ token: Token }> = ({ token }) => {
const [messageHistory, setMessageHistory] = useState<MessageEvent<any>[]>([]); const [messageHistory, setMessageHistory] = useState<MessageEvent<any>[]>([]);
const ref = useRef<HTMLDivElement>(null);
const { sendMessage, lastMessage, readyState } = useWebSocket(MOMO_IM_URL, { const { sendMessage, lastMessage, readyState } = useWebSocket(MOMO_IM_URL, {
heartbeat: { heartbeat: {
@ -57,12 +58,17 @@ export const Danmu: React.FC<{ token: Token }> = ({ token }) => {
} }
console.log(message); console.log(message);
setMessageHistory((prev) => prev.concat(message)); setMessageHistory((prev) => prev.concat(message));
if (ref.current) {
setTimeout(() => {
ref.current.scrollTop = ref.current.scrollHeight;
}, 0);
}
} }
} }
}, [lastMessage]); }, [lastMessage]);
return ( return (
<div className="h-[50vh] overflow-auto"> <div className="h-[50vh] overflow-auto" ref={ref}>
{messageHistory.map((message, idx) => ( {messageHistory.map((message, idx) => (
<MessageDispatcher key={idx} message={message} /> <MessageDispatcher key={idx} message={message} />
))} ))}