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

如何在React的.map遍历中选中第四个网格元素并添加col-start-2类

map 方法的回调可以接收第二个参数 index 表示当前元素的索引(从0开始计数),第四个元素对应的索引为3,你只需要在判断索引匹配时给对应元素添加 col-start-2 类即可,修改后的代码如下:

return (
  <Layout pageTitle='Projects'>
    <GridIndex>
      {data.allMdx.nodes.map((node, index) => (
        <article 
          key={node.id} 
          className={index === 3 ? 'col-start-2' : ''}
        >
          <Link to={`/projects/${node.slug}`}>
            <div>{node.frontmatter.title}</div>
            <GatsbyImage
              image={getImage(node.frontmatter.imageCover)}
              alt={node.frontmatter.imageCoverAlt}
              className='h-auto xs:square'
            />
          </Link>
        </article>
      ))}
    </GridIndex>
  </Layout>
);
};

如果你原本就需要给 <article> 标签加其他通用类名,可以用模板字符串拼接写法即可:

className={`你的通用类名 ${index === 3 ? 'col-start-2' : ''}`}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:54:04