解决方法:利用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、在定义路由的组件内引用该组件,代码如下:
render(){
return(
<Router>
<ScrollToTop>
<Route path='/' exact component={Index} />
<Route path='/name' component={Name} />
</ScrollToTop>
</Router>
),
};
网友评论