问题描述
我用 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) => (
/weatherIcon/${icon}.png)
在我改变的组件中
但在应用中没有显示。
问题是:如何显示本地图像而不是 Api 图像
解决方法
在 React 项目中有多种使用图像的方法。由于 React 遵循组件架构,因此我们在 React 中具有灵活性。
所以我们可以将图片(如果是SVG图片)表示为一个React组件,直接导入使用,也可以先导入一张图片,在img
标签的src
属性中使用。
请参阅本文以更好地理解并使用更适合您需求的方法。
betterprogramming.pub/how-to-display-images-in-react
注意: 有时在 NextJS 项目中,我观察到我们在使用 SVG 时必须使用 React Component 方法。此外,我们可以使用公共文件夹中的图像,如果它们是 .png
或 .pneg
等,并直接使用绝对路径来显示它们。
我的解决方案 我创造了新的康斯坦斯
const WeatherIcon = {
"01d": "/icons/01d.svg"
}
然后导入到组件中,
import{ WeatherIcon }from "utils/index";
并在 Img 标签中使用
<img className="weather_icon" src={WeatherIcon[data.weather[0].icon]}/>
感谢您的帮助