【问题标题】:How to iterate images on React?如何在 React 上迭代图像?
【发布时间】:2018-01-05 01:37:24
【问题描述】:

嗯,这个问题不言自明。我这里有这段代码(当然是在渲染中):

const images = [('http://placehold.it/100x100/76BD22'), ('http://placehold.it/100x100/76BD23')];

// ProductPage Views 
const ProductPageView = 
  <section className="page-section ps-product-intro">
    <div className="container">
      <div className="product-intro">
        <div className="product-intro__images">
          <div className="product-gallery">
            <ul className="product-gallery-thumbs__list">
              {images.map(function(image, imageIndex){
                return <li key={ imageIndex }>{image}</li>;
              })}
            </ul>
          </div>
        </div>
      </div>
    </div>
  </section>

问题是我不知道如何在数组上迭代这些图像。我的代码有什么问题?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我假设您想将它们显示为图像,对吧?那么你应该使用img标签。

    <ul className="product-gallery-thumbs__list">
       {images.map(function(image, imageIndex){
          return <img key={ imageIndex } src={ image } />
       })}
    </ul>
    

    【讨论】:

      【解决方案2】:

      您的数组是图像 URL 数组,而不是图像标签。因此,您的代码很接近,但您需要将图像放在列表项标记内的图像标记内。

      const images = [('http://placehold.it/100x100/76BD22'), ('http://placehold.it/100x100/76BD23')];
      // ProductPage Views 
      
      const ProductPageView = 
        <section className="page-section ps-product-intro">
          <div className="container">
            <div className="product-intro">
              <div className="product-intro__images">
                <div className="product-gallery">
                  <ul className="product-gallery-thumbs__list">
                    {images.map(function(imageSrc) {
                      return (
                        <li key={ imgSrc }>
                          <img src={ imgSrc } />
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </section>
      

      我也建议反对using an array index as a key in general。 imgSrc 是独一无二的,因此它会成为一个很好的密钥。

      此外,请确保在屏幕阅读器的img 中包含alt 属性。您可能希望像这样制作数组:

      const images = [
        { src: 'http://placehold.it/100x100/76BD22', alt: 'Your description here 1' }, 
        { src: 'http://placehold.it/100x100/76BD23', alt: 'Your description here 2' }
      ];
      
      // ...
      
      {images.map(function(imageProps) {
        return (
          <li key={ imageProps.src }>
            <img src={ imageProps.src } alt={ imageProps.alt } />
          </li>
        );
      })}
      

      【讨论】:

      • 就是这样!你太不可思议了!真的非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2017-08-16
      • 2018-09-29
      • 1970-01-01
      • 2015-03-11
      • 2021-09-27
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多