react 虚拟滚动列表hook实现例子

该博客展示了如何使用自定义React Hooks `useVirtual` 实现高性能的虚拟滚动列表,支持固定和动态高度的列表项。通过这个优化,即使在大数据量的情况下,也能保持流畅的用户体验。示例代码详细解释了钩子的用法,帮助开发者理解和应用虚拟列表技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图

在这里插入图片描述

使用例子

import React from 'react';
import useVirtual from './useVirtual';

const colors = ['#8868ff', '#24cdd0', '#ffc84e', '#fe657f', '#748cfd'];

export default () => {
  const [list1, containerProps1, wrapperProps1] = useVirtual({
    total: 9996,
    height: 280,
    itemHeight: 54,
  });
  const [list, containerProps, wrapperProps] = useVirtual({
    total: 9996,
    height: 280,
    itemHeight: i => (i % 2 === 0 ? 86 : 54),
  });
  return (
    <div>
      <Part>Item 定高</Part>
      <div {...containerProps1}>
        <div {...wrapperProps1}>
          {list1.map(({ style, index }) => (
            <div
              style={{
                ...style,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                background: colors[index % colors.length],
                borderBottom: '1px solid #e8e8e8',
              }}
              key={index}
            >
              {index + 1}
            </div>
          ))}
        </div>
      </div>
      <Space />
      <Part>Item 不定高</Part>
      <div {...containerProps}>
        <div {...wrapperProps}>
          {list.map(({ style, index }) => (
            <div
              style={{
                ...style,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                background: colors[index % colors.length],
                borderBottom: '1px solid #e8e8e8',
              }}
              key={index}
            >
              {index + 1}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

源码

https://github.com/Lemonreds/react-components/blob/master/src/hooks/useVirtual.js

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值