ScrollRestoration
<ScrollRestoration>
此组件将模拟浏览器在 loader 完成后对位置更改的滚动恢复。这可确保滚动位置在正确的时间恢复到正确的位置,即使跨域也是如此。
您应该只在 <Scripts/> 组件之前渲染其中一个。
import { Scripts, ScrollRestoration,} from "@remix-run/react";
export default function Root() { return ( <html> <body> {/* ... */} <ScrollRestoration /> <Scripts /> </body> </html> );}Props
获取密钥
可选。定义用于恢复滚动位置的键。
<ScrollRestoration getKey={(location, matches) => { // default behavior return location.key; }}/>讨论
使用location.key可模拟浏览器的默认行为。用户可以在堆栈中多次导航到同一个 URL,并且每个条目都会获得自己的滚动位置以进行恢复。
某些应用可能希望覆盖此行为并根据其他内容恢复位置。考虑一个有四个主要页面的社交应用:
/home/messages/notifications/search
如果用户从/home开始,向下滚动一点,单击导航菜单中的消息,然后单击导航菜单中的主页(而不是后退按钮!)历史记录堆栈中将有三个条目:
1. /home2. /messages3. /home默认情况下,React Router(和浏览器)将为1和3存储两个不同的滚动位置,即使它们具有相同的 URL。这意味着当用户从2导航到3时,滚动位置会转到顶部,而不是恢复到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 属性将传递给脚本标签以允许使用 CSP nonce。
<ScrollRestoration nonce={cspNonce} />防止滚动重置
当导航到新位置时,滚动位置将重置为页面顶部。您可以阻止链接和表单出现滚动到顶部行为:
<Link preventScrollReset={true} />;<Form preventScrollReset={true} />;