框架
版本

滚动恢复

哈希/页首滚动

开箱即用,TanStack Router 支持哈希滚动页首滚动,无需任何额外配置。

滚动到顶部和嵌套可滚动区域

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

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

对于无法通过document.querySelector(selector)简单解析的复杂选择器,您可以将返回HTML元素的函数传递给routerOptions.scrollToTopSelectors

tsx
const selector = () =>
  document
    .querySelector('#shadowRootParent')
    ?.shadowRoot?.querySelector('#main-scrollable-area')

const router = createRouter({
  scrollToTopSelectors: [selector],
})
const selector = () =>
  document
    .querySelector('#shadowRootParent')
    ?.shadowRoot?.querySelector('#main-scrollable-area')

const router = createRouter({
  scrollToTopSelectors: [selector],
})

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

滚动恢复

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

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

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

为了缓解这个问题,TanStack Router 提供了一个滚动恢复组件和钩子,它们为您处理监控、缓存和恢复滚动位置的过程。

它通过以下方式实现:

  • 监控 DOM 中的滚动事件
  • 将可滚动区域注册到滚动恢复缓存中
  • 监听适当的路由事件,以了解何时缓存和恢复滚动位置
  • 在缓存中存储每个可滚动区域的滚动位置(包括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 选项自定义用于缓存给定可滚动区域滚动位置的键。例如,这可以用于强制无论用户浏览器历史记录如何都使用相同的滚动位置。

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

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

旧版本(v1.121.34 之前)使用 state.key 作为默认键,但这已被弃用,转而使用 state.__TSR_key。目前,location.state.key 仍将用于兼容性,但在下一个主要版本中将被移除。

示例

您可以将滚动与路径名同步。

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,
})

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

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

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

const router = createRouter({
  getScrollRestorationKey: (location) => {
    const paths = ['/', '/chat']
    return paths.includes(location.pathname)
      ? location.pathname
      : location.state.__TSR_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钩子和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>
  )
}

滚动行为

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

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

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

const router = createRouter({
  scrollRestorationBehavior: 'instant',
})
我们的合作伙伴
Code Rabbit
Netlify
Neon
Clerk
Convex
Sentry
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

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

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

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