【问题标题】:Use image tag inside the for loop in ReactJs在 ReactJs 的 for 循环中使用图像标签
【发布时间】:2019-06-26 05:39:51
【问题描述】:

我有一个包含一组图像名称的数组。我可以使用console.log 打印所有图像,但不幸的是,当我尝试<img/> 时,它没有查看图像。

   for (let index = 0; index < array.length; index++) {
   const element = array[index];
   console.log(element)
     }

console.log(element)的输出

DSC_0000038.jpg 
DSC_0000040.jpg 
DSC_0000039.jpg 
DSC_0000047.jpg 
DSC_0000045.jpg 
DSC_0000049.jpg 
DSC_0000042.jpg 
DSC_0000041.jpg

如何解决我的问题?

【问题讨论】:

  • 可以发一下渲染方法吗?
  • @DFord 这是在渲染方法中
  • render: (record3) =&gt;{ for (let index = 0; index &lt; record3.split(",").length; index++) { const element = record3.split(",")[index]; console.log(element) } }
  • 你应该这样做:return array.map((image, index) =&gt; &lt;img src={image} key={index} /&gt;)。请注意,您不应该使用 index 作为键,但这只是为了这个示例,向您展示您应该将 key prop 放在这里。 (它应该是图像的一些唯一 ID)。如果没有这个道具,你会得到反应错误说:Each child in array or iterator should have unique "key" prop.

标签: reactjs


【解决方案1】:

做这样的事情:

    import React from 'react'

    const myImages = [
    "DSC_0000038.jpg",
    "DSC_0000040.jpg", 
    "DSC_0000039.jpg", 
    "DSC_0000047.jpg", 
    "DSC_0000045.jpg", 
    "DSC_0000049.jpg", 
    "DSC_0000042.jpg", 
    "DSC_0000041.jpg"
    ]


    export default class Images extends React.Component{

      constructor(props){
        super(props)
        this.state = {
          path : '/img/'
        }
      }

      render(){

        const images = myImages.map(
          (image, index) => <img src={this.state.path + image} key={index} alt="image" />
        )

        return(

          <section>
            {images}
          </section>

        )
      }

    }

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2021-07-12
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多