滚动还原到导航更改的顶部

时间:2019-03-11 23:59:35

标签: reactjs

使用react-router导航时,滚动出现问题。

当我导航到其他组件时,它保持上次导航时的滚动位置。但是,无论何时更改导航,我都希望它还原并从顶部开始。

 class App extends Component{
  render() {
   return(
    <BrowserRouter onUpdate={() => window.scrollTo(0, 0)} history={createBrowserHistory()}>
      <div style={{display: 'flex'}}>
        <div className='navBar'>
          <ul style={{listStyleType: 'none'}}>
            <li><Link to='/'>Home</Link></li>
            <li><Link to='/towns'>Towns</Link></li>
            <li><Link to='/pubs'>Pubs</Link></li>
            <li><Link to='/venues'>Venues</Link></li>
            <li><Link to='/cinemas'>Cinemas</Link></li>

          </ul>
        </div>

        <div style={{flex:1, padding:'0px'}}>
          {routes.map((route) => (
            <Route
              key={route.path}
              path={route.path}
              exact={route.exact}
              component={route.main}
              />
            ))}
          </div>
        </div>
      </BrowserRouter>
     )
   }
 }

但是它不起作用。我觉得问题出在我的导航风格,而不是window.scrollTo()片段。

2 个答案:

答案 0 :(得分:2)

我使用React钩子的解决方案

import { useEffect, useRef } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';

const ScrollIntoView = ({ children, location }) => {
  const prevLocation = useRef();

  useEffect(() => {
    if (prevLocation.current !== location.pathname) {
      window.scrollTo(0, 0);
      prevLocation.current = location.pathname;
    }
  }, [location]);

  return children;
};

ScrollIntoView.propTypes = {
  children: PropTypes.node,
  location: PropTypes.object
};

export default withRouter(ScrollIntoView);

答案 1 :(得分:0)

据我所知,由于react-router v4的存在,BrowserRouter没有onUpdate功能。

完成它的几种方法。这将是最简单的...

工作示例https://codesandbox.io/s/7mr12q2wz6(滚动到页面的最下方,然后单击链接)

components / ScrollIntoView.js

import { PureComponent } from "react";
import { withRouter } from "react-router-dom";

class ScrollIntoView extends PureComponent {
  componentDidMount = () => window.scrollTo(0, 0);

  componentDidUpdate = prevProps => {
    if (this.props.location !== prevProps.location) window.scrollTo(0, 0);
  };

  render = () => this.props.children;
}

export default withRouter(ScrollIntoView);

routes / index.js

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Links from "../components/Links";
import Home from "../components/Home";
import About from "../components/About";
import Contact from "../components/Contact";
import ScrollIntoView from "../components/ScrollIntoView";

export default () => (
  <BrowserRouter>
    <div>
      <ScrollIntoView>
        <Links />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/contact" component={Contact} />
        </Switch>
        <Links />
      </ScrollIntoView>
    </div>
  </BrowserRouter>
);

或者您可以在这里找到另一种方法:Scroll to the top of the page after render in react.js