reactjs 我应该怎么做才能在单击分页按钮后滚动到顶部?

rryofs0p  于 2023-01-12  发布在  React
关注(0)|答案(1)|浏览(117)

创建分页后,我希望在单击分页按钮时自动滚动到顶部。
使用onChange={handleChange}我尝试运行pageTopRef.current.scrollIntoView({ behavior: "smooth" });
但我得到了这个错误:
TypeError:无法读取null的属性(正在读取"scrollIntoView")

const outerTheme = createTheme({
  palette: {
    secondary: {
      main: blue[500],
    },
    primary: {
      main: "#ed6c02",
    },
  },
});

export default function MediaCard() {
  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 3500);
  }, []);

  const pageTopRef = useRef(null);
  const [loading, setLoading] = useState(true);
  const [currentpage, setCurrentpage] = useState(1);
  const [postsPerpage, setPostsPerpage] = useState(24);
  const lastPostIndex = currentpage * postsPerpage;
  const firstpostindex = lastPostIndex - postsPerpage;

  const handleChange = (event, value) => {
    setCurrentpage(value);
    pageTopRef.current.scrollIntoView({ behavior: "smooth" });
  };

  return (
    <div>
      <ul>
        <Container>
          <Grid container spacing={1}>
            {Myjson.slice(firstpostindex, lastPostIndex).map((item) => {
              return (

                     Some code
              );
            })}
          </Grid>
        </Container>
        <Stack alignItems="center" justifyContent="center">
          <Pagination
            count={Math.ceil(Myjson.length / postsPerpage)}
            variant="outlined"
            color="warning"
            sx={{ mt: 4, ml: -11 }}
            onChange={handleChange}
          />
        </Stack>
      </ul>
    </div>
  );
}

我应该怎么做才能在单击分页按钮后滚动到顶部?

5us2dqdw

5us2dqdw1#

假设页面的顶部也是窗口的顶部,也许可以尝试window.scrollTo,看看它是否有所改进。

const handleChange = (event, value) => {
  setCurrentpage(value);
  window.scrollTo({
    top: 0,
    left: 0,
    behavior: "smooth",
  });
};

相关问题