react如何在切換路由的時候,頁面在最頂部


vue有相關配置,但是因為用戶需要,reactRouter在之前的版本中舍棄了其配置,需要用戶自定義設置

 

方法:

創建一個組件,判斷切換后的頁面是否是最頂端

···

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

```
然后在app中引入該組件

```
return (
<Router>
<Switch>
<ScrollToTop>
<Route path='/' exact
render={token ? () => LayEditRouter : () => <Redirect to='/login' push/>}
/>
<Route path='/login' component={Login}/>
<Route path='/' render={props => LayEditRouter}/>
</ScrollToTop>
</Switch>
</Router>
);






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM