React项目中为AG Grid添加骨架加载器的实现问询
在React AG Grid中实现骨架加载器的可行方案
方案1:自定义Loading Cell Renderer(单元格级骨架)
如果需要给每个单元格单独添加骨架效果,你可以通过自定义loadingCellRenderer实现,核心是在加载状态下渲染占位行,并为每列指定骨架组件:
// 骨架单元格组件 const SkeletonCell = () => ( <div className="skeleton-cell"> <div className="skeleton-line"></div> </div> ); // 骨架样式(可放在CSS文件或styled-components中) .skeleton-cell { padding: 8px 12px; } .skeleton-line { width: 75%; height: 16px; background: linear-gradient(90deg, #f5f5f5 25%, #e8e8e8 50%, #f5f5f5 75%); background-size: 200% 100%; animation: skeleton-loading 1.5s infinite linear; border-radius: 4px; } @keyframes skeleton-loading { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } // Grid组件中使用 const MyAgGrid = () => { const [isLoading, setIsLoading] = useState(true); const [rowData, setRowData] = useState([]); // 模拟异步数据加载 useEffect(() => { const fetchData = async () => { // 替换为实际接口请求 const data = await new Promise(resolve => setTimeout(() => resolve([ { name: "张三", age: 28, email: "zhangsan@example.com" }, { name: "李四", age: 32, email: "lisi@example.com" } ]), 2000)); setRowData(data); setIsLoading(false); }; fetchData(); }, []); const columnDefs = [ { field: "name", headerName: "姓名", loadingCellRenderer: SkeletonCell }, { field: "age", headerName: "年龄", loadingCellRenderer: SkeletonCell }, { field: "email", headerName: "邮箱", loadingCellRenderer: SkeletonCell } ]; return ( <AgGridReact columnDefs={columnDefs} // 加载时渲染5个占位行,数量可按需调整 rowData={isLoading ? Array(5).fill({}) : rowData} rowHeight={40} /> ); };
方案2:自定义全屏加载覆盖层(整表级骨架)
如果需要在Grid上方覆盖整个骨架区域,可通过自定义loadingOverlayComponent实现,替代AG Grid默认的加载提示:
// 整表骨架覆盖层组件 const SkeletonOverlay = () => ( <div className="skeleton-overlay"> {Array(5).fill(0).map((_, idx) => ( <div key={idx} className="skeleton-row"> <div className="skeleton-col" style={{ width: "30%" }}></div> <div className="skeleton-col" style={{ width: "20%" }}></div> <div className="skeleton-col" style={{ width: "50%" }}></div> </div> ))} </div> ); // 覆盖层样式 .skeleton-overlay { display: flex; flex-direction: column; padding: 16px; gap: 12px; width: 100%; height: 100%; } .skeleton-row { display: flex; gap: 8px; } .skeleton-col { height: 20px; background: linear-gradient(90deg, #f5f5f5 25%, #e8e8e8 50%, #f5f5f5 75%); background-size: 200% 100%; animation: skeleton-loading 1.5s infinite linear; border-radius: 4px; } // Grid组件中使用 <AgGridReact columnDefs={columnDefs} rowData={rowData} // 清空默认加载模板 overlayLoadingTemplate={""} loadingOverlayComponent={SkeletonOverlay} // 控制覆盖层显示/隐藏 isLoading={isLoading} />
你之前失败的可能原因
- 使用
loadingCellRenderer时未设置占位rowData:AG Grid仅在存在行数据时才会渲染单元格骨架,需在加载状态下传入空对象数组作为占位行。 overlayTemplate写法问题:默认模板仅支持简单HTML,复杂骨架样式需通过自定义组件实现,而非直接写在模板字符串中。
内容的提问来源于stack exchange,提问作者complexpie
相关产品推荐
相关产品推荐

