当前位置: 首页 > news >正文

虚拟列表react-virtualized使用(npm install react-virtualized)

1. 虚拟化列表 (List)

// 1. 虚拟化列表 (List)

import { List } from 'react-virtualized';
import 'react-virtualized/styles.css'; // 只导入一次样式

// 示例数据
const list = Array(1000).fill().map((_, index) => ({
    id: index,
    name: `Item ${index}`,
    description: `This is item number ${index} in the list`
}));

function Index() {
    const rowRenderer = ({ index, key, style }) => {
        const item = list[index];
        return (
            <div key={key} style={style} className="list-item">
                <h3>{item.name}</h3>
                <p>{item.description}</p>
            </div>
        );
    };

    return (
        <List
            width={600} // 列表宽度
            height={400} // 列表高度
            rowCount={list.length} // 总行数
            rowHeight={80} // 每行高度
            rowRenderer={rowRenderer} // 行渲染函数
            overscanRowCount={5} // 预渲染的行数
        />
    )
}

export default Index;



2. 可变高度列表 (CellMeasurer)

// 2. 可变高度列表 (CellMeasurer)


import { List, CellMeasurer, CellMeasurerCache } from 'react-virtualized';
import 'react-virtualized/styles.css';

// 可变高度数据
const variableData = Array(500).fill().map((_, index) => ({
    id: index,
    title: `Item ${index}`,
    content: `This is item ${index}. `.repeat(Math.floor(Math.random() * 10) + 1)
}));

function Index() {
    // 创建测量缓存
    const cache = new CellMeasurerCache({
        defaultHeight: 60,
        fixedWidth: true
    });

    const rowRenderer = ({ index, key, parent, style }) => {
        const item = variableData[index];

        return (
            <CellMeasurer
                key={key}
                cache={cache}
                parent={parent}
                columnIndex={0}
                rowIndex={index}
            >
                <div style={style} className="variable-item">
                    <h3>{item.title}</h3>
                    <p>{item.content}</p>
                </div>
            </CellMeasurer>
        );
    };

    return (
        <List
            width={600} // 列表宽度
            height={400} // 列表高度
            deferredMeasurementCache={cache}
            rowHeight={cache.rowHeight} // 每行高度
            rowCount={variableData.length} // 总行数
            rowRenderer={rowRenderer} // 行渲染函数
            overscanRowCount={3} // 预渲染的行数
        />
    )
}

export default Index;


3. 无限加载列表 - 高度固定

// 3. 无限加载列表 - 高度固定

import React, { useState } from 'react';
import { List, AutoSizer } from 'react-virtualized';
import 'react-virtualized/styles.css';

function InfiniteLoadingList() {
  const [items, setItems] = useState(
    Array(50).fill().map((_, i) => ({ id: i, name: `Item ${i}` }))
  );
  const [loading, setLoading] = useState(false);

  const loadMoreItems = () => {
    if (loading) return;
    
    setLoading(true);
    
    // 模拟API调用
    setTimeout(() => {
      const newItems = Array(50).fill().map((_, i) => ({
        id: items.length + i,
        name: `Item ${items.length + i}`
      }));
      
      setItems(prev => [...prev, ...newItems]);
      setLoading(false);
    }, 1000);
  };

  const isRowLoaded = ({ index }) => index < items.length;

  const rowRenderer = ({ index, key, style }) => {
    if (!isRowLoaded({ index })) {
      return (
        <div key={key} style={style} className="loading-row">
          Loading...
        </div>
      );
    }
    
    const item = items[index];
    return (
      <div key={key} style={style} className="list-item">
        {item.name}
      </div>
    );
  };

  const onRowsRendered = ({ stopIndex }) => {
    if (stopIndex >= items.length - 10 && !loading) {
      loadMoreItems();
    }
  };

  return (
    <div style={{ height: '500px', width: '100%' }}>
      <AutoSizer>
        {({ width, height }) => (
          <List
            width={width}
            height={height}
            rowCount={items.length + 1} // +1 for loading row
            rowHeight={50}
            rowRenderer={rowRenderer}
            onRowsRendered={onRowsRendered}
            overscanRowCount={5}
          />
        )}
      </AutoSizer>
      {loading && <div className="loading-indicator">Loading more items...</div>}
    </div>
  );
}

export default InfiniteLoadingList;

4. 无限加载列表 - 高度不固定

// 4. 无限加载列表 - 高度不固定

http://www.dtcms.com/a/122230.html

相关文章:

  • 大模型Prompt提示词越狱相关知识
  • 一种替代DOORS在WORD中进行需求管理的方法 (二)
  • Vue:路由切换表格塌陷
  • SpringBoot 整合 MCP
  • 树莓派非桌面版无法ssh或vnc远程连接问题解决办法
  • 通过HTTP协议实现Git免密操作的解决方案
  • telophoto源码查看记录 三
  • 【回眸】Linux 内核 (十五) 之 多线程编程 上
  • 4月9日笔记
  • 2021-10-26 C++繁忙通信兵
  • Java 设计模式:原型模式详解
  • 使用雪花算法生成分布式唯一ID
  • Android 回答视频边播放边下载的问题
  • GMSL Strapping Pins CFG0/CFG1 应用
  • 【力扣刷题实战】外观数列
  • ragflow开启https访问:浏览器将自签证书添加到受信任的根证书颁发机构 ,当证书过期,还需要添加吗?
  • 第一部分——Docker篇 第六章 容器监控
  • vulnhub:sunset decoy
  • 洛谷普及B3691 [语言月赛202212] 狠狠地切割(Easy Version)
  • 优化 Web 性能:移除未使用的 CSS 规则(Unused CSS Rules)
  • The packaging for this project did not assign a file to the build artifact
  • 02.使用cline(VSCode插件)、continue(IDEA插件)、cherry-studio玩转MCP
  • Android里面开子线程的方法
  • OpenHarmony子系统开发 - 调测工具(二)
  • 柑橘病虫害图像分类数据集OrangeFruitDataset-8600
  • Python: 实现数据可视化分析系统
  • Coze平台 发布AI测试Agent的完整实现方案
  • redis_exporter服务安装并启动
  • STL-list链表
  • mac 苍穹外卖 后端初始 SkyApplication 报错