react虚拟滚动

复制代码
function VirtualList({ data, itemHeight, bufferSize = 5 }) {
  const [scrollTop, setScrollTop] = useState(0);
  const containerRef = useRef(null);
  
  // 计算可视区域范围
  const viewportHeight = containerRef.current?.clientHeight || 0;
  const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - bufferSize);
  const endIndex = Math.min(data.length, startIndex + Math.ceil(viewportHeight / itemHeight) + bufferSize * 2);

  // 动态渲染的条目
  const visibleItems = data.slice(startIndex, endIndex);

  return (
    <div 
      ref={containerRef}
      onScroll={(e) => setScrollTop(e.target.scrollTop)}
      style={{ height: '100%', overflow: 'auto' }}
    >
      {/* 占位容器,模拟完整列表高度 */}
      <div style={{ height: `${data.length * itemHeight}px` }}>
        {/* 实际渲染的内容 */}
        <div style={{ transform: `translateY(${startIndex * itemHeight}px)` }}>
          {visibleItems.map((item, index) => (
            <div key={item.id} style={{ height: `${itemHeight}px` }}>
              {item.content}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
  1. 缓冲区(bufferSize)​​:在可视区域外额外渲染少量条目,避免快速滚动时出现空白。

    1. 定高(itemHeight)​​:提前确定条目高度(或使用动态高度预测),简化位置计算。
    1. CSS Transform ​:用 translateY替代 top属性,利用GPU加速提升性能。
相关推荐
xiaofeichaichai1 小时前
Webpack
前端·webpack·node.js
问心无愧05131 小时前
ctf show web入门111
android·前端·笔记
唐某人丶1 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界2 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌2 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel3 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3113 小时前
https连接传输流程
前端·面试
徐小夕3 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
threelab3 小时前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器