猿问

如何在 URL 中传递变量值?

我正在尝试根据一些可变数据访问 URL。


{

  this.state.countries.map((country, key) => {

    return <a key={country.iso2}>

      <img src="https://www.countryflags.io/{country.iso2}/shiny/24.png" />

    </a>;

  });

}

上述 URL 中的值{country.iso2}是动态的。请帮我正确设置 URL 格式。


慕沐林林
浏览 141回答 5
5回答

繁花如伊

尝试模板文字。back tick注意and的使用$<img src=`https://www.countryflags.io/${country.iso2}/shiny/24.png`/>

HUX布斯

当您使用 jsx 时,您必须添加花括号,然后添加模板文字,然后添加由 包围的变量${},如下所示:let country = { iso2: "au" };ReactDOM.render(&nbsp; <img src={`https://www.countryflags.io/${country.iso2}/shiny/24.png`} />,&nbsp; root);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="root"></div>

缥缈止盈

正确的做法是使用模板文字如果您的值是动态的,那么使用back tick和$

慕田峪9158850

你可以这样做{this.state.countries.map((country, key) => {&nbsp; &nbsp; &nbsp; &nbsp;return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a key={country.iso2}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<img src=`https://www.countryflags.io/${country.iso2}/shiny/24.png`/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp;})}

摇曳的蔷薇

使用反引号和美元符号{this.state.countries.map((country, key) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a key={country.iso2}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src=`https://www.countryflags.io/${country.iso2}/shiny/24.png`/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp;})}
随时随地看视频慕课网APP

相关分类

Html5
我要回答