在每次转换时滚动到顶部

在每次转换时滚动到顶部

本文介绍了react-router 在每次转换时滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在导航到另一个页面时遇到问题,它的位置将保持与之前的页面一样.所以它不会自动滚动到顶部.我还尝试在 onChange 路由器上使用 window.scrollTo(0, 0) .我也使用 scrollBehavior 来解决这个问题,但它没有用.对此有什么建议吗?

I have an issue when navigating into another page, its position will remain like the page before. So it won't scroll to top automatically.I've also tried to use window.scrollTo(0, 0) on onChange router. I've also used scrollBehavior to fix this issue but it didn't work. Any suggestions about this?

推荐答案

2018 年的课程就是这样

ScrollToTop.js

ScrollToTop.js

import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, []);

  return (null);
}

export default withRouter(ScrollToTop);

用法:

<Router>
  <Fragment>
    <ScrollToTop />
    <Switch>
        <Route path="/" exact component={Home} />
    </Switch>
  </Fragment>
</Router>

ScrollToTop 也可以实现为包装组件:


ScrollToTop can also be implemented as a wrapper component:

ScrollToTop.js

ScrollToTop.js

import React, { useEffect, Fragment } from 'react';
import { withRouter } from 'react-router-dom';

function ScrollToTop({ history, children }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, []);

  return <Fragment>{children}</Fragment>;
}

export default withRouter(ScrollToTop);

用法:

<Router>
  <ScrollToTop>
    <Switch>
        <Route path="/" exact component={Home} />
    </Switch>
  </ScrollToTop>
</Router>

这篇关于react-router 在每次转换时滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:37