美文网首页react umi dva antd大前端
react-router路由跳转后,页面不在顶部的问题

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

作者: jack钱 | 来源:发表于2022-01-12 14:04 被阅读0次

    问题:在一个页面将滚动条滑动到底部后,使用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;
    

    相关文章

      网友评论

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

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