首页 > 解决方案 > 在底部时无法滚动元素

问题描述

在我的 React 项目中,我创建了某些元素,这些元素在到达页面底部时被添加。我在覆盖在主页上的新页面中制作了这个。

请参阅以下代码以供参考:

const PAGE_NUMBER = 1;
const [state, setState] = useState([]);
const [page, setPage] = useState(PAGE_NUMBER);

  useEffect(() => {
    document.addEventListener("scroll", () => {
      const windowRelativeBottom = document.documentElement.getBoundingClientRect()
        .bottom;
      // user scrolled enough
      if (windowRelativeBottom <= document.documentElement.clientHeight + 100) {
        setPage((pageCount) => pageCount + 1);
      }
    });
  }, []);

  useEffect(() => {
    fetch(`https://api.instantwebtools.net/v1/passenger?page=${page}&size=15`)
      .then((res) => res.json())
      .then((json) => setState([...state, ...json.data]));
  }, [page]);

  return (
 <Layout name="TEST SCROLL" show={false}> {/* <-- This is the page where I've rendered this component */}
      {state.length > 0 &&
        state.map((el, i) => (
          <div key={i} className="container">
            <h4>{el.id}</h4>
            <h4>{el.name}</h4>
          </div>
        ))}
    </Layout>
  );

在这里你可以看到 Layout 组件用于使其覆盖在主页上

布局页面.js

const navScrollStyle = makeStyles((theme) => ({
  root: {
    marginTop: "120px",
    display: "table",
    overflowY: "auto",
    maxWidth: "auto",
    justifyContent: "center"
  }
}));

const navBodyStyle = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    top: "0px",
    width: "100%",
    height: "100vh",
    textAlign: "center",
    background: "white",
    zIndex: "9999",
    height: "100%",
    overflowY: "auto",
    position: "absolute" {/* <-- When I remove this scrolls perfectly, but, BottomFooter is seen */}
  },
  menuButton: {
    marginRight: theme.spacing(2),
    color: "purple"
  },
  title: {
    flexGrow: 1,
    textAlign: "center",
    color: "black"
  }
}));

const gridClassStyle = makeStyles((theme) => ({
  root: {
    zIndex: "100",
    flexGrow: 1,
    position: "fixed",
    top: "0px",
    background: "white",
    flexWrap: "nowrap",
    boxShadow: "5px 10px 18px #888888"
  }
}));

const Layout = (props) => {
  const navBody = navBodyStyle();
  const navScroll = navScrollStyle();
  const gridClass = gridClassStyle();

  const NavPart = () => (
    <Grid className={gridClass.root} container spacing={3}>
      <BackButton />
      <NameHeader name={props.name} />
    </Grid>
  );
  return (
    <div className={navBody.root}>
      {NavPart()}
      <div className={navScroll.root}>{props.children}</div>
    </div>
  );
};

export default Layout;

正如您在上面看到的,注释position:'absolute'中的内容是使其覆盖在页面上的位置,但是,当删除滚动时会顺利进行,并且底部页脚页面可见,这是不被接受的。

那么有什么更好的解决方案来解决这个问题呢?

这是代码和框链接:https ://codesandbox.io/s/focused-wright-qlzgg

进入项目后,点击“测试”按钮

标签: javascriptreactjs

解决方案


推荐阅读