在位置更改时模拟浏览器的滚动恢复。应用程序应该只渲染一个这样的组件,并且应该放在 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)
一个返回用于滚动恢复的键的函数。这对于自定义滚动恢复逻辑很有用,例如仅使用路径名,以便后续导航到先前路径时可以恢复滚动。默认为 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
属性,用于在 <script>
元素上渲染。
在 sessionStorage
中存储滚动位置时使用的键。默认为 "react-router-scroll-positions"
。