You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MUI X Data Grid中实现无限滚动功能?

MUI X Data Grid 无限滚动实现实用技巧

实现方案

付费版本(Pro/Enterprise)实现方式

付费版本原生提供onRowsScrollEnd回调,无需自己监听滚动事件,直接绑定即可实现底部触发加载:

import { DataGridPro } from '@mui/x-data-grid-pro';
import { useState, useCallback } from 'react';

const InfiniteScrollGrid = () => {
  const [rows, setRows] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  const loadMoreRows = useCallback(async () => {
    if (isLoading) return; // 加锁避免重复请求
    setIsLoading(true);
    // 调用你的接口拉取下一页数据
    const nextPageRows = await fetch(`/api/your-data?page=${currentPage}`).then(res => res.json());
    setRows(prevRows => [...prevRows, ...nextPageRows]);
    setCurrentPage(prev => prev + 1);
    setIsLoading(false);
  }, [isLoading, currentPage]);

  return (
    <DataGridPro
      rows={rows}
      columns={yourColumnsConfig}
      onRowsScrollEnd={loadMoreRows}
      loading={isLoading}
      // 可选:配置底部加载阈值,默认0,单位像素
      scrollEndThreshold={200}
    />
  );
};

开源版本(MIT)实现方式

开源版本没有内置onRowsScrollEnd,可以自行监听表格虚拟滚动容器的滚动事件实现:

import { DataGrid } from '@mui/x-data-grid';
import { useState, useEffect, useRef } from 'react';

const InfiniteScrollGrid = () => {
  const gridRef = useRef(null);
  const [rows, setRows] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  // 绑定滚动监听
  useEffect(() => {
    const scrollContainer = gridRef.current?.querySelector('.MuiDataGrid-virtualScroller');
    if (!scrollContainer) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
      // 距离底部小于200px且没有加载中请求时触发加载
      if (scrollTop + clientHeight >= scrollHeight - 200 && !isLoading) {
        loadMoreRows();
      }
    };

    scrollContainer.addEventListener('scroll', handleScroll);
    return () => scrollContainer.removeEventListener('scroll', handleScroll);
  }, [isLoading]);

  const loadMoreRows = async () => {
    setIsLoading(true);
    const nextPageRows = await fetch(`/api/your-data?page=${currentPage}`).then(res => res.json());
    setRows(prevRows => [...prevRows, ...nextPageRows]);
    setCurrentPage(prev => prev + 1);
    setIsLoading(false);
  };

  return (
    <DataGrid
      ref={gridRef}
      rows={rows}
      columns={yourColumnsConfig}
      loading={isLoading}
    />
  );
};

避坑提示

  • 必须加请求状态锁,避免滚动到底部时触发多次重复请求
  • 不用关闭组件自带的虚拟滚动,MUI Data Grid默认支持的虚拟滚动可以保证万级以上数据也不会出现卡顿
  • 可以自定义底部加载占位行替换默认的整表loading,交互体验更流畅
  • 不需要配置pagination相关属性,无限滚动场景下显式分页会和滚动加载逻辑冲突

内容的提问来源于stack exchange,提问作者user805703

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 02:45:03