首页 > 解决方案 > scrollToTop 在反应中不起作用(codesandbox)

问题描述

作为反应,我试图让 scrollToTop 工作。

不知何故,它不起作用。

https://codesandbox.io/s/quiet-shape-5iov0?file=/src/App.js这是codesandbox。向下滚动,应该有一个按钮,称为click向上滚动,但它不起作用。

标签: javascriptreactjsreact-native

解决方案


如果您只需要滚动顶部,请尝试此操作。

  window.scrollTo({
      top: 0,
      left: 0,
      behavior: "smooth"
    });

功能

const nice = () => {
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: "smooth"
    });
  };

另一种使用方式scrollIntoView()

const nice = () => {
    document.querySelector("body").scrollIntoView({
      behavior: "smooth"
    });
  };

为了更好地理解,检查window.scrollTo


推荐阅读