reactjs InfiniteScroll(react-infinite-scroll-component)在新数据填充时会导致页面底部

f4t66c6m  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(159)

我正在使用InfiniteScroll(react-infinite-scroll-component)。这是相反的顺序。但每当我使用API加载新数据时,它都会导致页面底部。下面是我的代码:

<div
     id="scrollableDiv"
     style={{
       flex: 1,
       overflow: "auto",
       display: "flex",
       flexDirection: "column-reverse",
     }}
   >
     <InfiniteScroll
       dataLength={messageGroups.length}
       onScroll={e => {
         e.preventDefault();
         const scrollHeight = e.target.scrollHeight;
         const varHeight = e.target.scrollTop - e.target.clientHeight;
         console.log("varHeight", varHeight);
         if (scrollHeight + varHeight < 1) {
           onFetchPreviousMessages();
         }
       }}
       style={{ display: "flex", flexDirection: "column-reverse" }} //To put endMessage and loader to the top.
       id="scrollableDiv"
       ref={scrollableDiv}
       scrollableTarget="scrollableDiv"
     />
     <div ref={messageRef} />
     {!messageGroups.length && composeType === "help" && (
       <ExplorerLargeInfoBlock
         icon={<FaLifeRing />}
         header="Help Request"
         message="Need help? Send us a message below and someone on the project team will get back to you shortly."
       />
     )}
     {messageGroups.map(renderMessageGroup)}
</div>

I referred some posts where the div was being used, but not sure how to access the div.current in my case.

onFetchPreviousMessages is simply calling data API to fetch new data

字符串

sauutmhj

sauutmhj1#

要访问您的例子中的div.current,可以使用useRef钩子创建对scrollableDiv的引用。然后,您可以访问当前属性以获取底层DOM元素并操纵其滚动行为。

import { useRef } from "react";

const scrollableDiv = useRef(null);

<InfiniteScroll
  dataLength={messageGroups.length}
  next={onFetchPreviousMessages} // Use 'next' prop instead of 'onScroll'
  hasMore={true} // Assuming you have more data to load
  inverse={true} // Set this to true for reverse order
  loader={<h4>Loading...</h4>} // Optional: You can add a loading indicator
  scrollableTarget={scrollableDiv.current} // Pass the DOM element as the scrollable target
>
  {/* Render your message items here */}
</InfiniteScroll>

个字符

相关问题