简体   繁体   English

使用 ReactJS 映射的 json 文件的 img 标签中 src 属性内的正确语法是什么?

[英]What is the correct syntax inside the src property in a img tag for a mapped json file using ReactJS?

I want to import some images from a local JSON file to my component.我想将一些图像从本地 JSON 文件导入到我的组件中。 I want them to match with the data that I fetch from the API.我希望它们与我从 API 获取的数据相匹配。

My JSON file is:我的 JSON 文件是:

[
  {
    "id": 1,
    "dwarf": "/assets/races/dwarf.png",
    "slug": "dwarf"
  },
  {
    "id": 2,
    "elf": "/assets/races/elf.png",
    "slug": "elf"
  }
]

I have this for mapping the JSON file:我有这个用于映射 JSON 文件:

                {images.map((item, index) => (
                    <C.Image
                        key={index}
                        item={item}
                    >
                        <img src={`item.${data.slug}`} />
                        <img src={item.dwarf} />
                    </C.Image>

{data.slug} is fetched from the API and matches the property name that I pass to each image inside the JSON file. {data.slug}是从 API 获取的,并与我传递给 JSON 文件中的每个图像的属性名称相匹配。 When I insert <img src={item.dwarf} /> , I have the image displayed, but it is the same for all.当我插入<img src={item.dwarf} /> ,我显示了图像,但对所有人来说都是一样的。 When I insert <img src={`item.${data.slug}`} /> , the image is not displayed and at the console it shows <img src="item.dwarf"> <img src="item.elf"> , instead of the image.当我插入<img src={`item.${data.slug}`} /> ,图像不显示,在控制台显示<img src="item.dwarf"> <img src="item.elf"> ,而不是图像。 What is the syntax to make use of the {data.slug} replacing each name and displaying the image?使用{data.slug}替换每个名称并显示图像的语法是什么?

You can use bracket notation to dynamically access object properties.您可以使用括号表示法来动态访问对象属性。 It looks like this:它看起来像这样:

const obj = { foo: 123, bar: 321 }

const propName = 'foo'
const prop = obj[propName]

console.log(prop) // output: 123

So in your case:所以在你的情况下:

<img src={item[item.slug]} />

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

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