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

如何用React+Chakra-UI实现按颜色数量自动布局的Grid组件?

解决React + Chakra-UI Grid组件动态适配布局问题

直接根据传入的颜色数量动态生成gridTemplateColumns配置即可,因为最多仅6种颜色,完全可以针对性分场景处理:

核心思路

通过判断颜色数组的长度,给Grid组件设置对应的列模板规则,避开auto-fit/auto-fill带来的空白或强制单列问题。

实现代码

import { Grid, Box } from '@chakra-ui/react';

const ColorGrid = ({ colors }) => {
  const getGridColumns = () => {
    const count = colors.length;
    switch(count) {
      case 1:
        return '1fr';
      case 2:
      case 3:
      case 4:
        return 'repeat(2, 1fr)';
      case 5:
      case 6:
        return 'repeat(3, 1fr)';
      default:
        return 'repeat(2, 1fr)';
    }
  };

  return (
    <Grid
      templateColumns={getGridColumns()}
      gap={4}
      gridAutoFlow="dense"
    >
      {colors.map((color, index) => (
        <Box
          key={index}
          bg={color}
          h={24}
          gridColumn={colors.length === 3 && index === 2 ? 'span 2' : 'span 1'}
        />
      ))}
    </Grid>
  );
};

关键细节说明

  • gridAutoFlow="dense":让Grid自动填充布局空白区域,避免无效空隙
  • 动态gridColumn:当颜色数量为3时,第三个色块跨两列,刚好填满整行,解决奇数数量的空白问题
  • 分场景列模板:针对不同数量直接指定列数,比auto-fit/minmax更精准,适配最多6个元素的有限场景

简洁替代写法

如果不想用switch,也可以用对象映射简化逻辑:

const columnConfigs = {
  1: '1fr',
  2: 'repeat(2, 1fr)',
  3: 'repeat(2, 1fr)',
  4: 'repeat(2, 1fr)',
  5: 'repeat(3, 1fr)',
  6: 'repeat(3, 1fr)',
};

const getGridColumns = () => columnConfigs[colors.length] || 'repeat(2, 1fr)';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:13:22