用途:TanStack Virtual(React)是无头虚拟化库,用于渲染大型列表(100+ 项)、实现虚拟滚动与无限滚动信息流。
主要能力:提供 useVirtualizer 与 useWindowVirtualizer 两个 Hook,支持固定尺寸、运行时动态测量尺寸、窗口虚拟化、水平方向、lanes 多列(瀑布流)、命令式滚动(scrollToIndex、scrollToOffset)等。核心必填选项为 count、getScrollElement、estimateSize,其余可选。
使用方式:安装 npm install @tanstack/react-virtual。滚动容器需 overflow: auto 并设置显式高度/宽度;内层容器 position: relative 且高度为 virtualizer.getTotalSize();每个虚拟项 position: absolute,用 translateY/translateX 定位。动态尺寸项需加 data-index 并挂 ref={virtualizer.measureElement},且不要设置 height。React key 用 item.key。窗口虚拟化需设置 scrollMargin,并在 transform 中减去它。
关键选项:overscan(默认 1)、gap(默认 0,替代 CSS margin)、paddingStart/paddingEnd、horizontal、lanes、getItemKey、enabled、isRtl。
限制:动态尺寸项不可使用平滑滚动(文档标注的限制);动态测量项不要设置高度;滚动容器不可省略 overflow: auto。完整 API 与更多模式(水平、可变尺寸、瀑布流、粘性、无限滚动、SSR)见官方参考。