简体   繁体   中英

scrollToTop doesn't work in react (codesandbox)

In react, I am trying to make scrollToTop work.

Somehow, It doesn't work.

https://codesandbox.io/s/quiet-shape-5iov0?file=/src/App.js Here is the codesandbox. scroll down and there's should be button, called click which scrolls up, but it doesn't work.

Try this if you just need to scroll top.

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

function

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

Another way using scrollIntoView()

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

For better understanding, checkout window.scrollTo

The scrollTo is a window function so just attach it there:)

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

您可以像这样使用 window 对象滚动到顶部:

  window.scrollTo(0,0)

If you dont want to use window object

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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