React-Router 路由跳转后页面不在顶部的问题

1,878 阅读1分钟

解决方法:利用window.scrollTo(0, 0)

1、定义一个组件ScrollToTop(也可取其他名) 代码如下:

import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop);

2、在定义路由的组件内引用该组件,代码如下: