即使添加事件监听器后,自动滚动也无法在反应中工作

问题描述 投票:0回答:1

我正在尝试创建一个聊天应用程序,每当发送新消息时,它应该自动滚动..

但这对我不起作用。 我已经添加了一个事件监听器到

chatBox
,我在事件回调中做了console.log,即使它不起作用..

我也尝试像之前的事件监听器一样,console.log(chatBox.container)我在控制台中获取了div

这是代码:

基本上,我已经尝试过这个 但它不是自动滚动

const chatBox = useRef(null); // stores the refrence of any component inside a variable
useEffect(() => {
    console.log(chatBox.current);
    chatBox.current.addEventListener("DOMNodeInserted", (event) => {
      const { currentTarget: target } = event;
      target.scroll({ top: target.scrollHeight, behavior: "smooth" });
    });
  }, [chatMessages]);

我的分区:

 <div className="chat-container-header-btn" ref={chatBox}>
          <MoreVertIcon />
        </div>

我也从一篇文章中尝试过这个:

const scrollToBottom = () => {
    chatBox.current?.scrollIntoView({
      behavior: "smooth",
      block: "end",
      inline: "nearest",
    });
  };
  useEffect(() => {
    scrollToBottom();
  }, [chatMessages]);

javascript reactjs autoscroll
1个回答
0
投票

我尝试了很多方法,这是唯一能够在内容扩展时自动滚动 div 的方法:

第 1 步: 导入必要的参考资料

   import { useEffect, useRef } from "react";

第 2 步: 在函数组件内,声明 ref 常量

   const refDivAfterMessages = useRef<HTMLDivElement>(null);

第3步:在您的div容器内,在其内容之后,添加一个新的DIV并向其中添加您在上一步中声明的引用:

   <div ref={refDivAfterMessages} />

第 4 步: 定义您的 useEffect 并将其 DependencyList 设置为您的列表长度,使用 rollIntoView 提供滚动属性:

  useEffect(() => {
    if (props.messages.length) {
      refDivAfterMessages.current?.scrollIntoView({
        behavior: "smooth",
        block: "end",
      });
    }
  }, [props.messages.length]);

来源:https://reacthustle.com/blog/react-auto-scroll-to-bottom-tutorial

© www.soinside.com 2019 - 2024. All rights reserved.