简体   繁体   English

检测滚动到 div 顶部并溢出:在 ReactJs 中滚动

[英]Detect scrolled to top of div with overflow: scroll in ReactJs

I'm creating a messaging feature.我正在创建一个消息传递功能。 The conversation occupies only 100vh height minus the header - so, I have to make its overflow set to scroll.对话只占用 100vh 高度减去 header - 所以,我必须将其溢出设置为滚动。 How do I detect if the user scrolls to the topmost part of the conversation?如何检测用户是否滚动到对话的最顶部? I will fetch older messages once the user scrolls to the top.一旦用户滚动到顶部,我将获取较旧的消息。

I did some research but none of them are working.我做了一些研究,但没有一个有效。 I think they're only applicable for a scrollable page.我认为它们仅适用于可滚动页面。

The code snippet below is similar to what I am seeing over the web.下面的代码片段与我在 web 上看到的相似。 However, the scroll never gets triggered.但是,滚动永远不会被触发。

const top_ref = React.useRef < HTMLDivElement > null;

const trackScrolling = () => {
  console.log("scrolling");
};

React.useEffect(() => {
  document.addEventListener("scroll", trackScrolling);

  return () => {
    document.removeEventListener("scroll", trackScrolling);
  };
});

As pointed out by cloned , Intersection Observer does the job.正如cloned所指出的,Intersection Observer 完成了这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM