react18虚拟滚动列表

不依赖第三方,借用react18api和原生JS实现一个虚拟滚动列表,如果你的项目比较小,又不想引入第三方的框架,可以拿去用;
虚拟滚动.gif

style样式
    .record_list{
        // 这里是动态高度
        height: calc(100% - 116px);
        overflow-x: hidden;
        overflow-y: auto;
        position: relative;
        .render_box{
            // 布局设为绝对定位,后续使用translateY动态改变
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
        }
    }
核心HTML
     {/* 外层盒子 屏幕高度 可滚动*/}
    <div className={style.record_list} ref={scrollBoxRef} onScroll={virtualBoxScroll}>
        {/* 空盒子 撑起高度*/}
        <div style={{ height: `${recordList.length * renderItemHeight}px` }}></div>
        {/*实际渲染的列表记录*/}
        <div className={style.render_box}  
            style={{ transform: `translateY(${startIndex * renderItemHeight}px)` }}>
            {
                 renderList.map((item: any) => {
                    return <CallLogCard key={item.id} item={item}></CallLogCard>
                })
            }
        </div>
    </div>
逻辑代码
    /*****************初始化变量*****************/
    // 1.初始配置
    let expendCount = 4; // 多渲染数量
    let screenHeight = 700; // 渲染屏幕高度
    const renderItemHeight = 60; // 每条数据的固定高度

    // 2.滚动容器Ref
    const scrollBoxRef = useRef<any>(null);

    // 3.开始,结束渲染索引
    const [endIndex, setEndIndex] = useState(20);
    const [startIndex, setStartIndex] = useState(0);

    // 4.动态更新渲染列表
    const renderList = useMemo(
        () => recordList.slice(startIndex, endIndex),
        [startIndex, endIndex, recordList],
    );

    /*****************方法*****************/
    // 滚动监听
    const virtualBoxScroll = () => {
        // 滑动距离
        const scrollDistance = scrollBoxRef.current.scrollTop;
        // 计算新索引
        /*Math.floor()一个数向下取整*/
        const startIndex = Math.floor(scrollDistance / renderItemHeight);
        /*Math.ceil()一个数向上取整*/
        const endIndex =
        startIndex + Math.ceil(screenHeight / renderItemHeight) + expendCount; // 多渲染5条
        // 更新索引
        setStartIndex(startIndex);
        setEndIndex(endIndex);
    };
    // 历史记录列表
    const [recordList, setRecordList] = useState<any>([]);
    // 获取历史记录列表;
    const pullHistoryPage = () => {
        /*ajax*/
        setRecordList([...res.list]);
    };
    // 初始化滚动屏幕高度
    const handleInitScreenHeight = () => {
        screenHeight = scrollBoxRef.current.clientHeight;
        /*Math.ceil()一个数向上取整*/
        expendCount = Math.ceil(screenHeight / renderItemHeight);
    };
    useEffect(() => {
         // 拉取数据
         pullHistoryPage();
        // 初始化定位
        handleInitScreenHeight();
    }, []);
  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值