feat: 自动滚动
This commit is contained in:
parent
25b7dd0f82
commit
d723fc6cda
@ -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<MessageEvent<any>[]>([]);
|
||||
const ref = useRef<HTMLDivElement>(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 (
|
||||
<div className="h-[50vh] overflow-auto">
|
||||
<div className="h-[50vh] overflow-auto" ref={ref}>
|
||||
{messageHistory.map((message, idx) => (
|
||||
<MessageDispatcher key={idx} message={message} />
|
||||
))}
|
||||
|
Loading…
Reference in New Issue
Block a user