首页 > 解决方案 > 在数组中渲染图像

问题描述

我有一个 JSON Schema,其中包含我需要在 ReactJS 中渲染到轮播中的图像数组。

api.json

[
  {
    "id": "DR001",
    "propertyFullName": "8838, Brook St, NY",
    "propertyShortName": "Anchorage, AK 99501",
    "features": ["2 beds", "1 bath", "865 sqft"],
    "description": "data.",
    "images": [
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide1",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide2",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide3",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide4",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide5",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide6"
    ],
    "status": true
  },
  {
    "id": "DR002",
    "propertyFullName": "8838, Brook St, NY",
    "propertyShortName": "Anchorage, AK 99501",
    "features": ["2 beds", "1 bath", "865 sqft"],
    "description": "data.",
    "images": [
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide1",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide2",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide3",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide4",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide5",
      "http://placehold.it/1000x400/ffffff/c0392b/&text=slide6"
    ]
  }
]

我正在硬编码第一个数组,即features像这样

{APIData.map((apiData, index) => {
                  return (
                    <>
                      <Heading subtitle>
                        <span name={index}>{apiData.features[0]}</span>
                        <span class="middle-dot" aria-hidden="true">
                          &nbsp;
                        </span>
                        <span>{apiData.features[1]}</span>
                        <span class="middle-dot" aria-hidden="true">
                          &nbsp;
                        </span>
                        <span>{apiData.features[2]}</span> <br />
                        <span>
                          <p>{apiData.description}</p>
                        </span>
                      </Heading>
                      <hr />
                    </>
                  );
                })}

因为,我知道只有 3 个功能,但在 的情况下images,它是动态的。我怎么能克服这个?

图像正在另一个中渲染<div>,我尝试过这样的事情

            <Carousel {...settings}>
              {APIData.map((images, index) => {
                return (
                  <>{<img src={images.images} alt={index} />}</>
                );
              })}
            </Carousel>

标签: arraysjsonreactjscreate-react-app

解决方案


使用您已经拥有的代码,最终会像这样迭代每个属性的图像:

<Carousel {...settings}>
  {APIData.map((data, index) => {
     data.images.map((image, index) => {
        return <img key={index} src={image} alt={index} />
     } 
  })}
</Carousel>


推荐阅读