ScrollRestoration
本页内容

ScrollRestoration

摘要

参考文档 ↗

在位置更改时模拟浏览器的滚动恢复。应用程序应该只渲染一个这样的组件,并且应该放在 Scripts 组件的正前方。

import { ScrollRestoration } from "react-router";

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

此组件会渲染一个内联 <script> 以防止滚动闪烁。nonce 属性将被传递给 script 标签,以允许使用 CSP nonce。

<ScrollRestoration nonce={cspNonce} />

签名

function ScrollRestoration({
  getKey,
  storageKey,
  ...props
}: ScrollRestorationProps)

属性

getKey

一个返回用于滚动恢复的键的函数。这对于自定义滚动恢复逻辑很有用,例如仅使用路径名,以便后续导航到先前路径时可以恢复滚动。默认为 location.key。请参阅 GetScrollRestorationKeyFunction

<ScrollRestoration
  getKey={(location, matches) => {
    // Restore based on a unique location key (default behavior)
    return location.key

    // Restore based on pathname
    return location.pathname
  }}
/>

nonce

一个 nonce 属性,用于在 <script> 元素上渲染。

storageKey

sessionStorage 中存储滚动位置时使用的键。默认为 "react-router-scroll-positions"

文档和示例 CC 4.0
编辑