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

求助实现基于配置对象生成MUI Skeleton布局的函数

动态生成MUI Skeleton布局的实现方案

1. 定义配置对象结构

先明确配置格式,支持单条/批量生成Skeleton,同时可控制布局排列、间距等:

// 可选:用TypeScript添加类型约束
type SkeletonConfigItem = {
  variant?: 'text' | 'rectangular' | 'circular';
  width?: string | number;
  height?: string | number;
  count?: number; // 同类型Skeleton的生成数量
  inline?: boolean; // 是否横向排列
  spacing?: string; // 元素间间距,如'16px'
};

type SkeletonConfig = SkeletonConfigItem[];

2. 实现generateSkeleton函数

基于配置数组循环生成对应Skeleton组件,同时处理布局样式:

import { Skeleton, Box } from '@mui/material';

const generateSkeleton = (config) => {
  return config.map((item, groupIndex) => {
    const { 
      variant = 'text', 
      width, 
      height, 
      count = 1, 
      inline, 
      spacing = '8px' 
    } = item;

    // 批量生成同类型的Skeleton
    const skeletonList = Array.from({ length: count }).map((_, idx) => (
      <Skeleton
        key={`skeleton-${groupIndex}-${idx}`}
        variant={variant}
        width={width}
        height={height}
        style={{
          marginBottom: inline ? 0 : spacing,
          marginRight: inline ? spacing : 0
        }}
      />
    ));

    // 横向排列的组用flex布局包裹
    return inline ? (
      <Box key={`group-${groupIndex}`} display="flex" flexWrap="wrap">
        {skeletonList}
      </Box>
    ) : (
      <Box key={`group-${groupIndex}`}>{skeletonList}</Box>
    );
  });
};

3. 使用示例

把原来的固定布局转换成配置驱动的动态生成:

// 仪表盘加载占位的配置
const dashboardSkeletonConfig = [
  { variant: 'text', width: '100%', count: 3, spacing: '12px' }, // 3行文本占位
  { variant: 'rectangular', width: '48%', height: 120, count: 2, inline: true, spacing: '4%' }, // 2个并排矩形卡片
  { variant: 'circular', width: 60, height: 60, count: 4, inline: true, spacing: '16px' } // 4个并排圆形头像
];

// 在组件中调用
const Dashboard = ({ loading }) => {
  if (loading) {
    return <Box padding={2}>{generateSkeleton(dashboardSkeletonConfig)}</Box>;
  }
  // 渲染真实数据
  return <div>仪表盘内容</div>;
};

4. 扩展优化

  • 若需要嵌套布局,可给配置项添加children字段,实现递归生成嵌套结构
  • 可将通用样式抽成MUI的styled组件,减少函数内的style重复
  • 结合MUI的Grid组件,可实现更精准的响应式布局

内容的提问来源于stack exchange,提问作者Cypher or KJ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:50:34