简体   繁体   English

带有 javascript 的 img 标签的动态 src

[英]Dynamic src for img tag with javascript

I have a react-app that gets crypto API from some Provider Server and setState in currency variable and shows them in a table.我有一个反应应用程序,它从一些提供程序服务器和货币变量中的setState获取加密API并将它们显示在表格中。 I download each cryptocurrency icon and create a JSON file (cryptoIconSrc) to set img tag src dynamically.我下载每个加密货币图标并创建一个 JSON 文件 (cryptoIconSrc) 以动态设置img 标签src icons are SVG.图标是 SVG。 but they don't display on my table.但它们没有显示在我的桌子上。

here I set a condition to find the related icon from the JSON file这里我设置了一个条件从JSON文件中查找相关图标

currency.map((item) => {
                    let mapItem = item;
                    const temp = cryptoIconSrc.filter((item) => {
                      return item["symbol"] === mapItem["baseAsset"];
                    });

and here I set that related icon to img src在这里我将相关图标设置为 img src

                    <img
                    src={`${temp[0]["src"]}`}
                    width="20px"
                    height="20px"
                    />

but they don't display但他们不显示

I use require("./someDirectory/icon.png") in other sections of my app but in this case require(`${temp[0]["src"]}`) doesn't work and issue an error: module... not found我在我的应用程序的其他部分使用require("./someDirectory/icon.png")但在这种情况下require(`${temp[0]["src"]}`)不起作用并发出错误:模块...未找到

  <img
    src={`${temp[0]["src"]}`}
    key={`${temp[0]["src"]}`}
    width="20px"
    height="20px"
   />

Adding a key prop will do the trick.添加一个关键道具就可以了。

It seems like you are using back ticks in your code.似乎您在代码中使用了反引号。 That almost never works, try using single quotes.这几乎永远不会奏效,尝试使用单引号。 So not:所以不是:

src={`${temp[0]["src"]}`}

But:但:

src={'${temp[0]["src"]}'}

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

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