简体   繁体   English

onScroll 事件没有在反应 js 中触发,我做错了什么

[英]onScroll event not firing in react js, what am i doing wrong

My onScroll event is not firing in react js.我的 onScroll 事件没有在 react js 中触发。

I am trying to set infinite scrolling in react js, but my onScroll event is not firing away.我正在尝试在 react js 中设置无限滚动,但我的 onScroll 事件没有触发。

it fetches posts from api and send it to the Post component.它从 api 获取帖子并将其发送到 Post 组件。 and i am rendering the post in the Post component.我正在 Post 组件中渲染帖子。

Feed.js Feed.js

import { Box } from "@mui/material";
import Post from "./Post";
import About from "./About";
import { useEffect, useState } from "react";
import { getInfiniteScroll } from "../apis/posts";

const Feed = () => {
  const [data, setData] = useState([]);
  const [skip, setSkip] = useState(0);

  useEffect(() => {
    fetchPosts();
    document
      .getElementById("scroll_div")
      .addEventListener("scroll", handleScroll, true);

    // Remove the event listener
    return () => {
      document
        .getElementById("scroll_div")
        .removeEventListener("scroll", handleScroll, true);
    };
  }, [skip]);

  const fetchPosts = async () => {
    try {
      const newPosts = await getInfiniteScroll(skip);

      setData(newPosts);
    } catch (error) {
      console.log(error.message);
    }
  };

  const handleScroll = (e) => {
    const { offsetHeight, scrollTop, scrollHeight } = e.target;
    console.log(e.target);

    if (offsetHeight + scrollTop >= scrollHeight) {
      setSkip(data?.length);
    }
    console.log(skip);
  };

  return (
    <Box
      flex={4}
      sx={{ padding: { xs: "0", sm: "0px 20px " }, overflow: "auto" }}
      onScroll={handleScroll}>
      <Post post={data} />
      <Box
        sx={{
          display: { sm: "none", xs: "block" },
          justifyContent: "center",
          alignItems: "center",
          paddingBottom: "50px",
        }}>
        <About />
      </Box>
    </Box>
  );
};

export default Feed;

Please help !!请帮忙 !!

I don't know if onScroll is supported by material's Box component.我不知道材质的Box组件是否支持onScroll What you can instead do is use refs你可以做的是使用 refs

function App() {
  const ref = useRef()

  useEffect(() => {
    const handleScroll = (e) => {
      // Do your stuff here
    };
    
    ref.current?.addEventListener("scroll", handleScroll);
    return () => ref.current?.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <Box ref={ref} />
  );
}

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

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