简体   繁体   English

页面更改时的滚动恢复未完全滚动到顶部

[英]Scroll Restoration on page change doesn't fully scroll to top

Scroll restoration scrolls 8/10ths of the way up the page but not all the way.滚动恢复向上滚动页面的 8/10,但不是一直滚动。 Not sure if my ScrollToTop component is flawed or if I'm using the route and switch tags incorrectly in the App component.不确定我的 ScrollToTop 组件是否有缺陷,或者我是否在 App 组件中错误地使用了路由和切换标签。 Below are the ScrollToTop and App components respectively.下面分别是 ScrollToTop 和 App 组件。

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

export default ScrollToTop;
return (
    <div className="App">
      <Switch>
        <Route path='/explore'>
          <ScrollToTop />
          <Layout className='' currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Explore posts={posts} />
          </Layout >
        </Route>
        <Route path='/meta'>
          <ScrollToTop />
          <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Meta currentUser={currentUser} posts={posts} />
          </Layout>
        </Route>
        <Route path='/mana'>
          <ScrollToTop>
            <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
              <Mana currentUser={currentUser} posts={posts} />
            </Layout>
          </ScrollToTop>
        </Route>
        <Route path='/crypto'>
          <ScrollToTop />
          <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Crypto currentUser={currentUser} posts={posts} />
          </Layout>
        </Route>
        <Route path='/film'>
          <ScrollToTop />
          <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Film currentUser={currentUser} posts={posts} />
          </Layout>
        </Route> 
      </Switch>
    </div >
  );
}

export default App; 

If you want to use window object to perform scroll:如果要使用 window object 进行滚动:

window.scroll({top:0,behavior:'smooth'})

Try this:尝试这个:

document.querySelector('body').scrollIntoView({ 
  block: "start"
})

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

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