【问题标题】:React> locale img instead image from apiReact> locale img 而不是来自 api 的图像
【发布时间】:2021-07-24 13:20:54
【问题描述】:

我用https://openweathermap.org/ 开发一个SPA,所以我用

显示img
<img src={`http://openweathermap.org/img/w/${data.weather[0].icon}.png`}/>

而不是这个,我想显示我本地文件夹中的另一个图像。我创建了带有 index.js 的 utils 文件夹和另一个名为 weatherIcon 的文件夹,其图标位于 .svg index.js 我有

export const getWeatherIcon = (icon) =&gt; (/weatherIcon/${icon}.png)

在我更改的组件中

但在应用中不显示。

问题是:如何显示本地图像而不是Api图像

【问题讨论】:

标签: weather-api


【解决方案1】:

在 React 项目中有多种使用图像的方法。由于 React 遵循组件架构,因此我们在 React 中具有灵活性。 所以我们可以将图片(如果是SVG图片)表示为React Component,直接导入使用,也可以先导入一张图片在img标签的src属性中使用。

请参阅本文以更好地理解并使用更适合您需求的方法。

betterprogramming.pub/how-to-display-images-in-react

注意: 有时在 NextJS 项目中,我观察到我们在使用 SVG 时必须使用 React Component 方法。另外,如果是.png或.pneg等,我们可以使用公共文件夹中的图片,直接使用绝对路径显示。

【讨论】:

    【解决方案2】:

    我的解决方案 我创建了新的康斯坦斯

        const WeatherIcon = {
        "01d": "/icons/01d.svg"
       }
    

    然后导入到组件中,

    import{ WeatherIcon }from "utils/index";

    在Img标签中使用

    <img className="weather_icon" src={WeatherIcon[data.weather[0].icon]}/>
    

    感谢帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      相关资源
      最近更新 更多