我正在使用聊天应用程序,并且正在使用滚动条从底部到顶部加载较旧的消息。当收到新消息时,我想先检查用户是否位于div的底部,然后才使用scrollToBottom函数。如何获取用户的当前身高/位置?
https://www.npmjs.com/package/react-infinite-scroller
谢谢,欧姆里
很遗憾,已经有几天没有回复。这是我的解决方法:
我创建了一个名为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