美文网首页
react-router路由跳转后回到页面顶部的几种方法

react-router路由跳转后回到页面顶部的几种方法

作者: 潇湘轮回 | 来源:发表于2020-05-07 08:14 被阅读0次

遇到的问题

A页面跳转至B页面,B页面停留在A页面浏览的位置,未回到页面顶部。

问题分析

 在项目中使用的是 hashHistory,它是建立在 history 之上的,当路由发生变化时会记住原路由的状态,跳转新页面后默认停留在原页面的位置。

解决办法

1、路由跳转时,操作document中body的scrollTop。

代码片段

代码具体如下:

document.documentElement.scrollTop = document.body.scrollTop = 0;

2、使用withRouter,withRouter可以包装任何自定义组件,将react-router 的 history,location,match 三个对象传入。无需一级级传递react-router 的属性,当需要用的router 属性的时候,将组件包一层withRouter,就可以拿到需要的路由信息。

代码片段1

代码具体如下:

import {Component} from 'react';

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

class ScrollToTop extends Component {

  componentDidUpdate(prevProps, prevState, snapshot) {

    if (this.props.location.pathname!==prevProps.location.pathname){

      window.scrollTo(0,0)

    }

  }

 render () {

    return (

      this.props.children

    );

  }

}

export default withRouter(ScrollToTop);

如何引用:

代码片段2

项目中加入以上代码后问题解决!

相关文章

网友评论

      本文标题:react-router路由跳转后回到页面顶部的几种方法

      本文链接:https://www.haomeiwen.com/subject/tutoghtx.html