React虚拟滚动列表-原理剖析

虚拟滚动列表

在大数据量级渲染时常用到虚拟滚动,各大组件库也都支持,本文也将简单实现一个demo,剖析其原理。
在这里插入图片描述
demo中通过20个dom元素,实现了1000条数据的虚拟渲染。

原理

通过三个盒子搭配:

  1. 最外层盒子开启滚动,作为滚动列表视窗。
  2. 高度盒子渲染数据实际高度,但不渲染数据,实现滚动效果。
  3. 渲染盒子通过计算滚动距离,动态渲染应该展示的数据,并保持在视窗中。
    在这里插入图片描述

源码

RFC

import React, { useState, useRef, useMemo } from 'react';
import './index.less';

export default function Index() {
  // 初始配置
  const expendCount = 4; // 多渲染数量
  const screenHeight = 560; // 渲染屏幕高度
  const renderItemHeight = 35; // 每条数据的固定高度

  // 滚动容器Ref
  const scrollBoxRef = useRef(null);
  // 数据构造
  const data = new Array(1000).fill(0).map((_, index) => `${index + 1}`);

  // 开始,结束渲染索引
  const [endIndex, setEndIndex] = useState(20);
  const [startIndex, setStartIndex] = useState(0);
  // 渲染列表
  const renderList = useMemo(
    () => data.slice(startIndex, endIndex),
    [startIndex, endIndex],
  );

  // 滚动监听
  const virtualBoxScroll = () => {
    // 滑动距离
    const scrollDistance = scrollBoxRef.current.scrollTop;
    // 计算新索引
    const startIndex = Math.floor(scrollDistance / renderItemHeight);
    const endIndex =
      startIndex + Math.ceil(screenHeight / renderItemHeight) + expendCount; // 多渲染5条
    // 更新索引
    setStartIndex(startIndex);
    setEndIndex(endIndex);
  };

  return (
    <div className="virtual-wrap">
      {/* 外层盒子 屏幕高度 可滚动*/}
      <div
        className="virtual-scroll-wrap"
        ref={scrollBoxRef}
        style={{ height: `${screenHeight}px` }}
        onScroll={virtualBoxScroll}
      >
        {/* 滚动盒子 渲染高度 空盒子 撑起高度*/}
        <div
          className="scroll-box"
          style={{ height: `${data.length * renderItemHeight}px` }}
        ></div>

        {/* 显示盒子 实际渲染条目 */}
        <div
          className="render-box"
          style={{
            transform: `translateY(${startIndex * renderItemHeight}px)`,
          }}
        >
          {renderList?.map((item) => (
            <div
              className="scroll-item"
              style={{ height: `${renderItemHeight}px` }}
              key={item}
            >
              <span></span>
              {item}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Style

.virtual-wrap{
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: black;
    height: 100vh;
    overflow: hidden;
    box-sizing: border-box;
    border: 1px solid pink;
    .virtual-scroll-wrap{
       width: 300px;
       border: 4px solid skyblue;
       overflow-y: auto;
       position: relative;
       background-color: azure;
       .render-box{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
       }
       .scroll-item{
        display: flex;
        align-items: center;
        box-sizing: border-box;
        padding:0 20px;
        color: #2b2b2b;
        border-bottom:1px solid #2b2b2b ;
        background-color: azure;
        box-shadow: 0 0 4px #ccc;
        span{
            display: inline-block;
            margin-right: 15px;
            border-radius: 50%;
            height: 16px;
            width: 16px;
            background-color: pink;
        }
       }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React-virtualized是一个非常流行的React库,它可以帮助我们实现大数据量的虚拟滚动效果。下面是一个使用React-virtualized实现虚拟滚动的表格的示例代码: 首先,我们需要安装React-virtualized库: ``` npm install react-virtualized --save ``` 然后,我们需要引入Table和Column组件: ``` import { Table, Column } from 'react-virtualized'; ``` 接下来,我们可以定义一个数据源,例如: ``` const list = [ { name: '张三', age: '18', address: '北京市海淀区' }, { name: '李四', age: '20', address: '北京市朝阳区' }, { name: '王五', age: '22', address: '北京市西城区' }, // ... // 这里可以添加更多的数据 ]; ``` 然后,我们可以定义一个Table组件,指定它的rowCount和rowGetter属性: ``` <Table rowCount={list.length} rowGetter={({ index }) => list[index]} > ``` 接下来,我们可以添加一些Column组件,定义每一列的属性: ``` <Column label="姓名" dataKey="name" width={100} /> <Column label="年龄" dataKey="age" width={100} /> <Column label="地址" dataKey="address" width={200} /> ``` 最后,我们需要在Table组件中添加一些属性,以启用虚拟滚动: ``` <Table rowCount={list.length} rowGetter={({ index }) => list[index]} headerHeight={20} rowHeight={30} width={600} height={400} > ``` 在上面的代码中,我们设置了headerHeight和rowHeight属性来指定表头和每一行的高度,width和height属性用于指定表格的宽度和高度。React-virtualized会自动根据这些属性来计算出需要渲染的行数,并且只渲染当前可见的行,以实现虚拟滚动的效果。 完整的代码示例: ``` import React, { Component } from 'react'; import { Table, Column } from 'react-virtualized'; const list = [ { name: '张三', age: '18', address: '北京市海淀区' }, { name: '李四', age: '20', address: '北京市朝阳区' }, { name: '王五', age: '22', address: '北京市西城区' }, // ... // 这里可以添加更多的数据 ]; class VirtualTable extends Component { render() { return ( <Table rowCount={list.length} rowGetter={({ index }) => list[index]} headerHeight={20} rowHeight={30} width={600} height={400} > <Column label="姓名" dataKey="name" width={100} /> <Column label="年龄" dataKey="age" width={100} /> <Column label="地址" dataKey="address" width={200} /> </Table> ); } } export default VirtualTable; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值