2017-07-28 30 views
0

那麼,這個問題是非常明顯的。我有這樣的代碼在這裏(內部渲染,當然):如何在React上迭代圖像?

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> 

的事情是我不知道如何在陣列上重複這些圖像。我的代碼有什麼問題?

回答

0

您的數組是一個圖像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是獨一無二的,所以它會成爲一個很好的鑰匙。

此外,確保屏幕閱讀器包含上的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> 
); 
})} 
+0

就是這樣!你真不可思議!非常感謝你! –

0

我假設你想將它們顯示爲圖像,對吧?您應該使用img標籤。

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