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

如何在React.js中实现每行展示3张卡片的动态响应式网格组件

问题核心原因

你当前代码的问题主要有两个:

  • 单个卡片组件内部嵌套了完整的Container + Row结构,导致每个卡片都会独占一行容器
  • 你设置的md={3}对应一行放4张卡片,要实现一行3张的效果,12栅格系统下应该设置为md={4}(12/3=4)

代码调整方案

Reactstrap 基于 Bootstrap 栅格开发,Row 默认自带 flex-wrap: wrap 属性,只要每个列宽度设置正确,卡片满3个后会自动换行,不需要你手动处理分行逻辑,调整代码如下:

1. 改造卡片组件

移除单个卡片外层的容器、行、列结构,只保留卡片本身的逻辑,同时支持接收外部传参自定义卡片内容:

import {
    Card, CardImg, CardText, CardBody,
    CardTitle, CardSubtitle, Button
} from 'reactstrap';

const INNERCARD = (props) => {
    const { imgSrc, title, subtitle, content } = props;
    return (
        <Card>
            <CardImg top width="100%" src={imgSrc || "/assets/318x180.svg"} alt="Card image cap"/>
            <CardBody>
                <CardTitle tag="h5">{title || "Card title"}</CardTitle>
                <CardSubtitle tag="h6" className="mb-2 text-muted">{subtitle || "Card subtitle"}</CardSubtitle>
                <CardText>{content || "Some quick example text to build on the card title and make up the bulk of the card's content."}</CardText>
                <Button>Button</Button>
            </CardBody>
        </Card>
    );
};

export default INNERCARD;

2. 父组件中调用渲染列表

在需要展示卡片列表的页面,统一用Container + Row包裹,循环渲染带md={4}的列包裹卡片即可:

import { Container, Row, Col } from 'reactstrap';
import INNERCARD from './INNERCARD';

// 你的卡片数据,可从接口获取
const cardList = [
  { id: 1, title: '卡片1', imgSrc: '/xxx/1.svg' },
  { id: 2, title: '卡片2', imgSrc: '/xxx/2.svg' },
  { id: 3, title: '卡片3', imgSrc: '/xxx/3.svg' },
  { id: 4, title: '卡片4', imgSrc: '/xxx/4.svg' },
  // 更多卡片数据...
]

const CardList = () => {
  return (
    <Container className="my-4">
      <Row g={4}> {/* g是栅格间距,可根据需要调整 */}
        {cardList.map(item => (
          <Col md={4} className="mb-4" key={item.id}>
            <INNERCARD {...item} />
          </Col>
        ))}
      </Row>
    </Container>
  )
}

export default CardList;

可选:手动拆分每行的实现方案

如果你有特殊需求(比如需要给每行单独加样式、加行级操作等),需要手动按3个一组拆分数据渲染多行,可以用数组分片的方式实现:

const CardList = () => {
  // 每3个卡片分为一组
  const rowGroups = Array.from({ length: Math.ceil(cardList.length / 3) }, (_, i) =>
    cardList.slice(i * 3, i * 3 + 3)
  );

  return (
    <Container className="my-4">
      {rowGroups.map((rowCards, rowIndex) => (
        <Row g={4} key={rowIndex} className="mb-4">
          {rowCards.map(item => (
            <Col md={4} key={item.id}>
              <INNERCARD {...item} />
            </Col>
          ))}
        </Row>
      ))}
    </Container>
  )
}

内容的提问来源于stack exchange,提问作者Abdul Hanan Asif

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 18:54:03