React Router v7 已發布。 查看文件
ScrollRestoration
本頁面內容

<ScrollRestoration>

此元件會在 loader 完成後,在位置變更時模擬瀏覽器的滾動恢復。這確保了滾動位置會在正確的時間恢復到正確的位置,即使跨網域也是如此。

您應該只渲染一個此元件,就在 <Scripts/> 元件之前。

import {
  Scripts,
  ScrollRestoration,
} from "@remix-run/react";

export default function Root() {
  return (
    <html>
      <body>
        {/* ... */}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

屬性

getKey

選填。定義用於恢復滾動位置的鍵。

<ScrollRestoration
  getKey={(location, matches) => {
    // default behavior
    return location.key;
  }}
/>
討論

使用 location.key 模擬瀏覽器的預設行為。使用者可以在堆疊中多次導覽至相同的 URL,並且每個條目都有自己的滾動位置可以恢復。

有些應用程式可能想要覆寫此行為,並根據其他內容恢復位置。考慮一個有四個主要頁面的社交應用程式

  • "/home"
  • "/messages"
  • "/notifications"
  • "/search"

如果使用者從 "/home" 開始,向下滾動一點,點擊導覽選單中的「訊息」,然後點擊導覽選單中的「首頁」(不是返回按鈕!),則歷史堆疊中將會有三個條目

1. /home
2. /messages
3. /home

預設情況下,React Router(和瀏覽器)會為 13 儲存兩個不同的滾動位置,即使它們具有相同的 URL。這表示當使用者從 23 導覽時,滾動位置會回到頂部,而不是恢復到 1 中的位置。

這裡一個可靠的產品決策是保持使用者在首頁動態消息上的滾動位置,無論他們如何到達那裡(返回按鈕或新的連結點擊)。為此,您會想要使用 location.pathname 作為鍵。

<ScrollRestoration
  getKey={(location, matches) => {
    return location.pathname;
  }}
/>

或者,您可能只想對某些路徑使用路徑名稱,而對其他所有路徑使用正常行為

<ScrollRestoration
  getKey={(location, matches) => {
    const paths = ["/home", "/notifications"];
    return paths.includes(location.pathname)
      ? // home and notifications restore by pathname
        location.pathname
      : // everything else by location like the browser
        location.key;
  }}
/>

nonce

<ScrollRestoration> 渲染一個內聯 <script> 以防止滾動閃爍。nonce 屬性將傳遞到 script 標籤,以允許使用 CSP nonce。

<ScrollRestoration nonce={cspNonce} />

防止滾動重置

當導覽到新位置時,滾動位置會重置到頁面頂部。您可以防止連結和表單的「滾動到頂部」行為

<Link preventScrollReset={true} />;
<Form preventScrollReset={true} />;

另請參閱:<Form preventScrollReset><Link preventScrollReset>

文件和範例根據以下條款授權 MIT