react-router路由跳转后,页面不在顶部的问题

问题:在一个页面将滚动条滑动到底部后,使用react-router跳转路由,发现新页面的滚动条保持在底部,并不在顶部
Github 中有这个问答:Github Issue:Scroll to top on route change?
原因是:React Router 不维护 scroll position
解决方案:在layouts组件中添加如下代码

// 解决跳转新页面滚动条不在顶部的问题
useEffect(() => {
  if (document && history?.location?.pathname != '/home') {  // 可以排除不需要置顶的页面
    if (document?.documentElement || document?.body) {
      document.documentElement.scrollTop = document.body.scrollTop = 0;  // 切换路由时手动置顶
    }
  }
}, [history?.location?.pathname]);

layout组件

import React, { useEffect } from 'react'

const Index: React.FC = (props) => {
  // 解决跳转新页面滚动条不在顶部的问题
  useEffect(() => {
    if (document && history.location.pathname != '/home') {
      if (document?.documentElement || document?.body) {
        document.documentElement.scrollTop = document.body.scrollTop = 0;
      }
    }
  }, [history.location.pathname]);

  const renderBody = () => {
    const { children } = props;
    return (
      <React.Fragment>
        {children}
      </React.Fragment>
    );
  }

  return (
    <React.Fragment>
      {renderBody()}
    </React.Fragment>
  )
}

export default Index;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容