refactor: 优化 useScrollToBottom

This commit is contained in:
dingjunjie 2023-06-24 16:37:29 +08:00
parent 35ba898c97
commit 9278d7f851

View File

@ -3,8 +3,8 @@ import React, {
useState, useState,
useRef, useRef,
useEffect, useEffect,
useLayoutEffect,
useMemo, useMemo,
useCallback,
} from "react"; } from "react";
import SendWhiteIcon from "../icons/send-white.svg"; import SendWhiteIcon from "../icons/send-white.svg";
@ -341,15 +341,15 @@ function useScrollToBottom() {
// for auto-scroll // for auto-scroll
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
const [autoScroll, setAutoScroll] = useState(true); const [autoScroll, setAutoScroll] = useState(true);
const scrollToBottom = () => { const scrollToBottom = useCallback(() => {
const dom = scrollRef.current; const dom = scrollRef.current;
if (dom) { if (dom) {
setTimeout(() => (dom.scrollTop = dom.scrollHeight), 1); requestAnimationFrame(() => dom.scrollTo(0, dom.scrollHeight));
} }
}; }, []);
// auto scroll // auto scroll
useLayoutEffect(() => { useEffect(() => {
autoScroll && scrollToBottom(); autoScroll && scrollToBottom();
}); });