【问题标题】:Wanted to pass parameter in <img> src attribute URL in ReactJS?想要在 ReactJS 的 <img> src 属性 URL 中传递参数?
【发布时间】:2021-08-09 09:40:01
【问题描述】:

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

import React, {useState,useEffect} from 'react';
import { Button } from 'react-bootstrap';

const TimeZoneComponent = () => {

const [data, setData] = useState([]);
const [city,setCity] = useState('');
const [printCity, setPrintCity] = useState(false);


const clickfn = () =>
{
    setPrintCity(true);
    if(printCity)
    {
        timeZone(city);
    }
}


async function timeZone(city) {
    await fetch(`http://worldtimeapi.org/api/timezone/Asia/${city}`)
    .then((response)=>response.json())
    .then((json)=>{
        //console.log(json);
        setData(json);
    })
}



useEffect(()=> {
        timeZone();
},[])

let mystr = JSON.stringify(data.datetime);

console.log("city typed  =  "+city);

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("/shiny/64.png");
}



return(
    <>
    <div className="timezone">       
        <div id="timezone-input">
            <label>Type Asian City Here..
                <br/>
            <input type="text" placeholder=" Type city here.." onChange={(event)=>setCity(event.target.value)}/>
                <br/>
            <Button className="timezone-button" onClick={()=>clickfn()} >Get Current DateTime</Button>
            </label>
        </div>
        Date: {mystr?.slice(1,11)} <br/>
        Time: {mystr?.slice(12,20)} <br/>
        Timezone: {data.timezone}
        <div>
            //Here I want to pass parameter in src of<img>
            <img src={readySRC({city})} alt="Country flag"/>
            ///////////
        </div>
    </div>
    </>
);

}
export default TimeZoneComponent;

有人帮忙怎么做吗?

【问题讨论】:

  • 如果你使用 fetch 和 then,没有理由使用 async await。

标签: javascript node.js reactjs image react-hooks


【解决方案1】:
<img src={readySRC({city})} alt="Country flag"/>

readSRC({city}) 表示

readSRC({
   city: city
});

在你的代码中应该是

readSRC(city) 

【讨论】:

  • 它有效,但是当我在同一代码中输入城市时,我得到延迟响应,我们有什么方法可以加快 timeZone API 的 API 响应。
  • @MohitMaroliyaB17CS036,延迟响应只是网络延迟,您的代码有其他问题,img总是有错误的来源。
猜你喜欢
  • 2021-10-12
  • 1970-01-01
  • 2019-03-23
  • 2014-06-29
  • 2020-10-16
  • 1970-01-01
  • 2021-08-12
  • 2015-07-11
  • 2020-12-12
相关资源
最近更新 更多