如何获得当前滚动高度-react-infinite-scroller

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

我正在使用聊天应用程序,并且正在使用滚动条从底部到顶部加载较旧的消息。当收到新消息时,我想先检查用户是否位于div的底部,然后才使用scrollToBottom函数。如何获取用户的当前身高/位置?

https://www.npmjs.com/package/react-infinite-scroller

谢谢,欧姆里

javascript reactjs chat infinite-scroll
1个回答
1
投票

很遗憾,已经有几天没有回复。这是我的解决方法:

我创建了一个名为isBottom的布尔值,并将onScroll = {handleScroll}函数附加到我的消息分区。

const [isBottom, setIsBottom] = useState(true);

const scrollToBottom = (behavior) => {
messagesEndRef.current.scrollIntoView();
};

const handleScroll = (e) => {
const bottom =
  e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
  setIsBottom(true);
} else {
  setIsBottom(false);
  } 
};

消息div:

      <div className="msg_list" onScroll={handleScroll}>
    <InfiniteScroll
      loadMore={loadMore}
      initialLoad={true}
      hasMore={hasMoreItems}
      loader={<LoadingAnimation key={0} />}
      useWindow={false}
      isReverse={true}
    >
      {messages}
      <div ref={messagesEndRef} />
    </InfiniteScroll>
  </div>

然后我添加了一个useEffect来处理我的消息数组中的更改(从道具到达)

  useEffect(() => {
if (isBottom) {
  scrollToBottom();
} else {
  setUnreadMessages((unreadMessages) => unreadMessages + 1);
 }
}, [messageList]);

*顺便说一句,您还需要将scrollTobottom函数连接到您的发送消息框中,因为如果您是发送消息的人,则无论如何都应该scrollToBottom

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