【问题标题】:Wanted to pass parameter in <img> src attribute URL?想要在 <img> src 属性 URL 中传递参数?
【发布时间】:2021-10-12 12:46:42
【问题描述】:

我想在 react 组件中 &lt;img&gt; 的 src 属性的 URL 中传递 code 参数。我已经完成了以下实现,但它在控制台中显示 invalid src

import React, {useState,useEffect} from 'react';
.
.
.
 
.
.

const cityToCodeMatcher = (city) => {
    let code;
    if(city === "Kolkata") code='IN';
    else if(city === "Tokyo") code='JP';
    return code;
}

const readySRC = (city) => {
    let temp =  "https://www.countryflags.io/".concat(cityToCodeMatcher(city));
    return temp.concat("/flat/64.png");
}



return(
    <>
    <div className="timezone">       
       <div>

这里我想在&lt;img&gt;的src中传递参数

            <img src={readySRC} alt="Country flags"/>
        </div>
    </div>
    </>
);

}
export default TimeZoneComponent;

有人帮忙怎么做吗?

【问题讨论】:

    标签: javascript html reactjs image src


    【解决方案1】:

    readySRC 是一个函数src 的值需要是一个字符串

    readySRC 如果你调用它会返回一个字符串,并且它期望被调用时带有一个参数。

    <img src={readySRC(something)} alt="Country flags"/>
    

    【讨论】:

    • 但我希望城市变量作为参数传入 URL,以便我输入哪个城市,我得到国家代码(根据 if else 条件)。 @昆汀
    • @MohitMaroliyaB17CS036 - 然后你需要提供一个地方供用户输入,以及一些代码来存储他们在状态中输入的内容,然后读取状态以填充something
    • 我正在这样做,在代码共享codeshare.io/K8WJ1o查看下面的完整代码
    • @MohitMaroliyaB17CS036 — 该页面是空白的。在问题本身中提供minimal reproducible example
    【解决方案2】:

    您应该使用城市名称调用函数。像这样。

    <img src={readySRC('Kolkata')} alt="Country flags"/>
    

    通过here了解更多关于函数的信息

    【讨论】:

    • 但我希望城市变量作为参数传入 URL,以便我输入哪个城市,我得到国家代码(根据 if else 条件)。 @Amruth
    • 正如您提到的@Amruth ,只需从您的临时变量中删除?city=
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2014-06-29
    • 2020-10-16
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多