React实现虚拟列表的优秀库介绍

在 React 中,有一些优秀的库可以帮助你实现高效的虚拟列表渲染。以下是几个常用的库:

1. react-window

react-window 是一个轻量级的虚拟列表库,适用于大多数虚拟列表需求。它提供了简单易用的 API 和良好的性能。

安装

shell 复制代码
npm install react-window

示例代码

javascript 复制代码
import React, { useCallback } from 'react';
import { FixedSizeList as List } from 'react-window';

const generateUniqueKey = () => `${new Date().getTime()}-${Math.random().toString(36).substr(2, 9)}`;

const DATA_LIST = Array.from({ length: 100000 }, (_, index) => ({
  key: generateUniqueKey(),
  slogan: `Item ${index + 1}`,
  bgColor: `hsl(${Math.random() * 360}, 100%, 75%)`
}));

const ITEM_HEIGHT = 35;

const Row = ({ index, style }) => (
  <div style={{ ...style, backgroundColor: DATA_LIST[index].bgColor }}>
    {DATA_LIST[index].slogan}
  </div>
);

const VirtualListPage = () => (
  <List
    height={window.innerHeight}
    itemCount={DATA_LIST.length}
    itemSize={ITEM_HEIGHT}
    width={'100%'}
  >
    {Row}
  </List>
);

export default VirtualListPage;

2. react-virtualized

react-virtualized 是一个功能强大的虚拟列表库,提供了更多的功能和配置选项,适用于复杂的虚拟列表需求。

安装

shell 复制代码
npm install react-virtualized

示例代码

javascript 复制代码
import React from 'react';
import { List } from 'react-virtualized';

const generateUniqueKey = () => `${new Date().getTime()}-${Math.random().toString(36).substr(2, 9)}`;

const DATA_LIST = Array.from({ length: 100000 }, (_, index) => ({
  key: generateUniqueKey(),
  slogan: `Item ${index + 1}`,
  bgColor: `hsl(${Math.random() * 360}, 100%, 75%)`
}));

const ITEM_HEIGHT = 35;

const rowRenderer = ({ key, index, style }) => (
  <div key={key} style={{ ...style, backgroundColor: DATA_LIST[index].bgColor }}>
    {DATA_LIST[index].slogan}
  </div>
);

const VirtualListPage = () => (
  <List
    width={window.innerWidth}
    height={window.innerHeight}
    rowCount={DATA_LIST.length}
    rowHeight={ITEM_HEIGHT}
    rowRenderer={rowRenderer}
  />
);

export default VirtualListPage;

3. react-virtual

react-virtual 是一个现代的虚拟列表库,提供了简单的 API 和良好的性能。

安装

shell 复制代码
npm install @tanstack/react-virtual

示例代码

javascript 复制代码
import React from 'react';
import { useVirtual } from '@tanstack/react-virtual';

const generateUniqueKey = () => `${new Date().getTime()}-${Math.random().toString(36).substr(2, 9)}`;

const DATA_LIST = Array.from({ length: 100000 }, (_, index) => ({
  key: generateUniqueKey(),
  slogan: `Item ${index + 1}`,
  bgColor: `hsl(${Math.random() * 360}, 100%, 75%)`
}));

const ITEM_HEIGHT = 35;

const VirtualListPage = () => {
  const parentRef = React.useRef();

  const rowVirtualizer = useVirtual({
    size: DATA_LIST.length,
    parentRef,
    estimateSize: React.useCallback(() => ITEM_HEIGHT, []),
  });

  return (
    <div
      ref={parentRef}
      style={{
        height: '100vh',
        width: '100%',
        overflow: 'auto',
      }}
    >
      <div
        style={{
          height: `${rowVirtualizer.totalSize}px`,
          width: '100%',
          position: 'relative',
        }}
      >
        {rowVirtualizer.virtualItems.map(virtualRow => (
          <div
            key={virtualRow.index}
            ref={virtualRow.measureRef}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${ITEM_HEIGHT}px`,
              transform: `translateY(${virtualRow.start}px)`,
              backgroundColor: DATA_LIST[virtualRow.index].bgColor,
            }}
          >
            {DATA_LIST[virtualRow.index].slogan}
          </div>
        ))}
      </div>
    </div>
  );
};

export default VirtualListPage;

4. antd 库:优秀的 React 库,这里不多介绍,详情看官网。

总结

  • react-window:轻量级,适用于大多数虚拟列表需求。
  • react-virtualized:功能强大,适用于复杂的虚拟列表需求。
  • react-virtual:现代化,提供简单的 API 和良好的性能。
  • antd 库:优秀的 React 库,不多介绍。

根据你的具体需求选择合适的库,可以大大简化虚拟列表的实现,并提高性能。

相关推荐
踩着两条虫几秒前
VTJ.PRO「AI + 低代码」应用开发平台的后端模块系统
前端·人工智能·低代码
Java陈序员2 分钟前
运维必备!一款全平台可用的服务器管理利器!
linux·react.js·docker
pany7 分钟前
程序员近十年新年愿望,都有哪些变化?
前端·后端·程序员
朱昆鹏12 分钟前
IDEA Claude Code or Codex GUI 插件【开源自荐】
前端·后端·github
HashTang12 分钟前
买了专业屏只当普通屏用?解锁 BenQ RD280U 的“隐藏”开发者模式
前端·javascript·后端
双向3313 分钟前
Agent智能体:2026年AI开发者必须掌握的自主系统革命
前端
мо仙堡杠把子ご灬13 分钟前
【无标题】
javascript
布列瑟农的星空13 分钟前
通用语法校验器tree-sitter——C++语法校验实践
前端
用户812748281512014 分钟前
libgui中的BufferQueueProducer加入堆栈CallStack编译报错问题-大厂企业实战项目难题
前端
明月_清风15 分钟前
从"请求地狱"到"请求天堂":alovajs 如何用 20+ 高级特性拯救前端开发者
前端·后端