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

React TSX如何向CSS传动态参数?适配数组长度实现Grid居中

解决React TSX中根据数组长度动态设置CSS Grid列数的问题

需求:使用CSS Grid布局时,当数组元素数量为1、2或3个时,在md断点下元素需保持居中显示,要根据数组长度动态设置grid-template-columns的值。

React TSX代码

<div className={styles.testWrap}>
  <div className={styles.testGrid}>
    {array.map((value, index) => {
      return (
        <div className={styles.logoBox} key={index}>
          <div
            onClick={() => router.push({ pathname: `./brand/${brand.id}` })}
            className={styles.logoContainer}
          >
            <NextImage src={brand.logoUrl} width={180} height={180} alt="pic" />
          </div>
        </div>
      );
    })}
</div>

原始CSS代码

.testWrap {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    background-color: pink;
    .testGrid {
        display: grid;
        width: 100%;
        gap: 24px;
        justify-content: center;
        margin-bottom: 130px;
        @include sm {
            width: fit-content;
            margin: 0 auto;
            grid-template-columns: auto auto;
            grid-template-rows: auto auto;
            margin-bottom: 197px;
        }
        @include md {
            // grid-template-columns: auto auto auto; if array number is three
            // grid-template-columns: auto auto; if array number is two
            // grid-template-columns: auto; if array number is one
            grid-template-columns: params; // How do I get dynamic params over here ?
            justify-content: center;
            grid-gap: 55px;
            width: 100%;
            margin-bottom: 195px;
        }
    }
}

解决方案

方法一:动态添加className

在TSX中根据数组长度给testGrid元素附加专属类名,再在CSS中针对md断点编写对应样式:

  1. 修改TSX代码:
<div className={`${styles.testGrid} ${styles[`grid-${array.length}`]}`}>
  1. 补充CSS的md断点样式:
@include md {
    justify-content: center;
    grid-gap: 55px;
    width: 100%;
    margin-bottom: 195px;
    
    &.grid-1 {
        grid-template-columns: auto;
    }
    &.grid-2 {
        grid-template-columns: auto auto;
    }
    &.grid-3 {
        grid-template-columns: auto auto auto;
    }
}

方法二:使用CSS变量(推荐)

通过React内联样式给元素注入CSS变量,在CSS中直接引用该变量生成对应列数:

  1. 修改TSX代码:
<div 
  className={styles.testGrid}
  style={{ '--column-count': array.length } as React.CSSProperties}
>
  1. 修改CSS的md断点代码:
@include md {
    grid-template-columns: repeat(var(--column-count), auto);
    justify-content: center;
    grid-gap: 55px;
    width: 100%;
    margin-bottom: 195px;
}

这种方式简洁高效,repeat()函数会直接根据变量值生成对应数量的列,完美匹配1、2、3个元素的需求。

方法三:内联样式结合媒体查询

如果需要更精细的断点控制,可以用媒体查询钩子判断当前环境,再动态设置内联样式:

  1. 引入媒体查询钩子(以MUI为例,也可自行实现):
import { useMediaQuery } from '@mui/material';
  1. 在组件内判断断点并生成列数配置:
const isMd = useMediaQuery('(min-width: [你的md断点宽度值])');
const gridColumns = isMd ? 
  array.length === 1 ? 'auto' : 
  array.length === 2 ? 'auto auto' : 'auto auto auto' : 
  undefined;
  1. 给testGrid设置内联样式:
<div 
  className={styles.testGrid}
  style={{ gridTemplateColumns: gridColumns } as React.CSSProperties}
>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:17:02