vue與react當路由頁面跳轉時滾動位置不對的處理

在我們開發react或者vue項目的時候會發現當切換路由進行頁面跳轉的時候如果在前一個頁面將滾動條滾到了最下面然後進行跳轉那麼接下來的那個頁面也會默認滾動在最下面。這個時候我們就需要處理一下。

在處理之前我們首先需要知道原因在哪裏:

原因是因爲虛擬dom的算法問題,導致不會更新scroll

解決方法:
在你的外層框架監聽history.location.pathname的變化,只要變了那就將body或者其他某元素的scrollTop設置爲0。

具體代碼【react + antd項目代碼展示】:

useEffect(() => {
    if (document) {
      if (document?.documentElement || document?.body) {
        document.documentElement.scrollTop = document.body.scrollTop = 0;
      }
      if (document.getElementsByClassName('antd-pro-layouts-basic-layout-layoutContent')?.[0]) { // 找你自己框架主體樣式
        document.getElementsByClassName('antd-pro-layouts-basic-layout-layoutContent')[0].scrollTop = 0;
      }
    }
  }, [history?.location?.pathname]);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章