框架
版本

滚动位置恢复

Hash/页面顶部滚动

开箱即用,TanStack Router 支持 hash 滚动和页面顶部滚动,无需任何额外配置。

滚动到顶部 & 嵌套滚动区域

默认情况下,滚动到顶部模仿浏览器的行为,这意味着成功导航后,只有 window 本身会滚动到顶部。然而,对于许多应用来说,由于高级布局,主要的滚动区域通常是嵌套的 div 或类似元素。如果您希望 TanStack Router 也为您滚动这些主要的滚动区域,您可以添加选择器,使用 routerOptions.scrollToTopSelectors 来定位它们

tsx
const router = createRouter({
  scrollToTopSelectors: ['#main-scrollable-area'],
})
const router = createRouter({
  scrollToTopSelectors: ['#main-scrollable-area'],
})

这些选择器是 window 之外的补充处理,window 当前无法禁用。

滚动位置恢复

滚动位置恢复是在用户导航回页面时恢复页面滚动位置的过程。这通常是基于标准 HTML 网站的内置功能,但对于 SPA 应用程序来说可能难以复制,因为

  • SPA 通常使用 history.pushState API 进行导航,因此浏览器不知道本地恢复滚动位置
  • SPA 有时会异步渲染内容,因此浏览器在内容渲染完成后才知道页面的高度
  • SPA 有时会使用嵌套的滚动容器来强制特定的布局和功能。

不仅如此,应用程序通常在应用内有多个滚动区域,而不仅仅是 body。例如,聊天应用程序可能有可滚动的侧边栏和可滚动的聊天区域。在这种情况下,您可能希望独立地恢复这两个区域的滚动位置。

为了缓解这个问题,TanStack Router 提供了滚动位置恢复组件和 Hook,用于处理监控、缓存和恢复滚动位置的过程。

它通过以下方式实现:

  • 监控 DOM 中的滚动事件
  • 将滚动区域注册到滚动位置恢复缓存
  • 监听适当的 router 事件,以了解何时缓存和恢复滚动位置
  • 在缓存中存储每个滚动区域的滚动位置(包括 windowbody
  • 在成功导航后,在 DOM 绘制之前恢复滚动位置

这听起来可能很多,但对您来说,它非常简单,如下所示:

tsx
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  scrollRestoration: true,
})
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  scrollRestoration: true,
})

注意

<ScrollRestoration /> 组件仍然有效,但已被弃用。

自定义缓存键

与 Remix 自己的滚动位置恢复 API 保持一致,您还可以使用 getKey 选项自定义用于缓存给定滚动区域滚动位置的 key。例如,这可以用于强制使用相同的滚动位置,而不管用户的浏览器历史记录如何。

getKey 选项接收来自 TanStack Router 的相关 Location 状态,并期望您返回一个字符串来唯一标识该状态的滚动测量值。

默认的 getKey(location) => location.state.key!,其中 key 是为历史记录中每个条目生成的唯一键。

示例

您可以将滚动同步到 pathname

tsx
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  getScrollRestorationKey: (location) => location.pathname,
})
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  getScrollRestorationKey: (location) => location.pathname,
})

您可以有条件地仅同步某些路径,然后对其余路径使用 key

tsx
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  getScrollRestorationKey: (location) => {
    const paths = ['/', '/chat']
    return paths.includes(location.pathname)
      ? location.pathname
      : location.state.key!
  },
})
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  getScrollRestorationKey: (location) => {
    const paths = ['/', '/chat']
    return paths.includes(location.pathname)
      ? location.pathname
      : location.state.key!
  },
})

阻止滚动位置恢复

有时您可能希望阻止滚动位置恢复发生。为此,您可以利用以下 API 上提供的 resetScroll 选项

  • <Link resetScroll={false}>
  • navigate({ resetScroll: false })
  • redirect({ resetScroll: false })

resetScroll 设置为 false 时,下次导航的滚动位置将不会被恢复(如果导航到堆栈中现有的历史记录事件),也不会重置到顶部(如果是堆栈中新的历史记录事件)。

手动滚动位置恢复

在大多数情况下,您不需要做任何特殊的事情即可使滚动位置恢复工作。但是,在某些情况下,您可能需要手动控制滚动位置恢复。最常见的示例是虚拟化列表。

要手动控制整个浏览器窗口中虚拟化列表的滚动位置恢复

tsx
function Component() {
  const scrollEntry = useElementScrollRestoration({
    getElement: () => window,
  })

  // Let's use TanStack Virtual to virtualize some content!
  const virtualizer = useWindowVirtualizer({
    count: 10000,
    estimateSize: () => 100,
    // We pass the scrollY from the scroll restoration entry to the virtualizer
    // as the initial offset
    initialOffset: scrollEntry?.scrollY,
  })

  return (
    <div>
      {virtualizer.getVirtualItems().map(item => (
        ...
      ))}
    </div>
  )
}
function Component() {
  const scrollEntry = useElementScrollRestoration({
    getElement: () => window,
  })

  // Let's use TanStack Virtual to virtualize some content!
  const virtualizer = useWindowVirtualizer({
    count: 10000,
    estimateSize: () => 100,
    // We pass the scrollY from the scroll restoration entry to the virtualizer
    // as the initial offset
    initialOffset: scrollEntry?.scrollY,
  })

  return (
    <div>
      {virtualizer.getVirtualItems().map(item => (
        ...
      ))}
    </div>
  )
}

要手动控制特定元素的滚动位置恢复,您可以使用 useElementScrollRestoration Hook 和 data-scroll-restoration-id DOM 属性

tsx
function Component() {
  // We need a unique ID for manual scroll restoration on a specific element
  // It should be as unique as possible for this element across your app
  const scrollRestorationId = 'myVirtualizedContent'

  // We use that ID to get the scroll entry for this element
  const scrollEntry = useElementScrollRestoration({
    id: scrollRestorationId,
  })

  // Let's use TanStack Virtual to virtualize some content!
  const virtualizerParentRef = React.useRef<HTMLDivElement>(null)
  const virtualizer = useVirtualizer({
    count: 10000,
    getScrollElement: () => virtualizerParentRef.current,
    estimateSize: () => 100,
    // We pass the scrollY from the scroll restoration entry to the virtualizer
    // as the initial offset
    initialOffset: scrollEntry?.scrollY,
  })

  return (
    <div
      ref={virtualizerParentRef}
      // We pass the scroll restoration ID to the element
      // as a custom attribute that will get picked up by the
      // scroll restoration watcher
      data-scroll-restoration-id={scrollRestorationId}
      className="flex-1 border rounded-lg overflow-auto relative"
    >
      ...
    </div>
  )
}
function Component() {
  // We need a unique ID for manual scroll restoration on a specific element
  // It should be as unique as possible for this element across your app
  const scrollRestorationId = 'myVirtualizedContent'

  // We use that ID to get the scroll entry for this element
  const scrollEntry = useElementScrollRestoration({
    id: scrollRestorationId,
  })

  // Let's use TanStack Virtual to virtualize some content!
  const virtualizerParentRef = React.useRef<HTMLDivElement>(null)
  const virtualizer = useVirtualizer({
    count: 10000,
    getScrollElement: () => virtualizerParentRef.current,
    estimateSize: () => 100,
    // We pass the scrollY from the scroll restoration entry to the virtualizer
    // as the initial offset
    initialOffset: scrollEntry?.scrollY,
  })

  return (
    <div
      ref={virtualizerParentRef}
      // We pass the scroll restoration ID to the element
      // as a custom attribute that will get picked up by the
      // scroll restoration watcher
      data-scroll-restoration-id={scrollRestorationId}
      className="flex-1 border rounded-lg overflow-auto relative"
    >
      ...
    </div>
  )
}

滚动行为

要控制在页面之间导航时的滚动行为,您可以使用 scrollBehavior 选项。这允许您使页面之间的过渡变为瞬间完成,而不是平滑滚动。滚动位置恢复行为的全局配置与浏览器支持的选项相同,即 smoothinstantauto(更多信息请参阅 MDN)。

tsx
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  scrollBehavior: 'instant',
})
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  scrollBehavior: 'instant',
})
订阅 Bytes

您的每周 JavaScript 新闻。每周一免费发送给超过 10 万名开发者。

Bytes

无垃圾邮件。随时取消订阅。