简体   繁体   English

如何在 React js 中将数据动态添加到网格中

[英]How to add data dynamically to the grid in React js

I want to be able to add images to a grid in sets of 3 but instead it is creating 3 sets of each image This is my code我希望能够以 3 组的形式将图像添加到网格中,但它会为每个图像创建 3 组这是我的代码

    const data = [
    {
      image:
        "https://d25u15mvjkult8.cloudfront.net/videos/7265406/images/500/dOlh05avp978ye6iGOid.jpg",
      id: 1,
    },
    {
      image:
        "https://d25u15mvjkult8.cloudfront.net/videos/7265203/images/500/955tjRfCGzpQyNZM3Kiz.jpg",
      id: 2,
    },
    {
      image:
        "https://d25u15mvjkult8.cloudfront.net/videos/7261533/images/500/PBHl35kwCbsoO27St6tP.jpg",
      id: 3,
    },
];


{data.map((item, index) => {
    return (
      <Col xl={12}>
        <Row>
          <Col xl={6}>
            <img
              src={item.image}
              alt="First slide"
              width={"100%"}
              height={600}
            />
          </Col>
          <Col xl={6}>
            <img src={item.image} width={"100%"} height={300} />
            <img src={item.image} width={"100%"} height={300} />
          </Col>
        </Row>
      </Col>
    );
  })}

This is my output这是我的 output 在此处输入图像描述

This is the desired result这是想要的结果

在此处输入图像描述

And if there are more than 3 images it should automatically create a row of images with similar structure.如果有超过 3 个图像,它应该自动创建一行具有相似结构的图像。

{data.map((item, index) => {
    return (
      <Col xl={12}>
        <Row>
          {index % 2 === 0 && <Col xl={6}>
            <img
              src={item.image}
              alt="First slide"
              width={"100%"}
              height={600}
            />
          </Col>}
          {index % 2 !== 0 && <Col xl={6}>
            <img
              src={item.image}
              alt="First slide"
              width={"100%"}
              height={600}
            />
          </Col>}
        </Row>
      </Col>
    );
  })}

Basically, you are doing it the correct way but you are looping all the items 3 times without condition, so it shows each image three times,基本上,您正在以正确的方式进行操作,但是您将所有项目无条件循环 3 次,因此每个图像显示 3 次,
In the above solution, I am looping through data and Col is taking 6 so It would be adjusted according to the condition.在上述解决方案中,我正在循环数据,而 Col 取 6,因此会根据条件进行调整。 Please check the responsiveness too.请检查响应能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM