【问题标题】:Why is the first method working but second isn't?为什么第一种方法有效而第二种方法无效?
【发布时间】:2022-02-07 14:15:05
【问题描述】:

第一种方法:

const getWeatherIcon = (iconParameter) => {
   const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png`
   return <img src={icon} alt={iconParameter} />
  }

<div className="weathericon">
       {getWeatherIcon(weather.weather[0].icon)} //Ex: weather.weather[0].icon=50n
</div>

第二种方法:

const getWeatherIcon = (iconParameter) => {
    const icon = `assets/weather/${iconParameter}.svg`
    return <img src={icon} alt={iconParameter} />
  }

<div className="weathericon">
     {getWeatherIcon(weather.weather[0].main)} //Ex: weather.weather[0].main=Haze
</div>

这是我的项目目录

src
│   App.js
│   index.css
│   index.js   
│
└───assets
    └───weather
    |  |    Haze.svg 
    │  |    Clear.svg
    │  |    Rain.svg
    |  
    └───bg
        |   file111.png
        |   file112.png

忽略关注

看起来你的帖子主要是代码;请添加更多细节。 看起来您的帖子主要是代码;请添加更多细节。 看起来您的帖子主要是代码;请添加更多细节。 看起来您的帖子主要是代码;请添加更多详细信息。

【问题讨论】:

  • Webpack 不知道您的 assets 文件夹,因为它没有被导入。浏览器将尝试寻找相对于网络“根”的/assets/weather/&lt;your&gt;.svg,但它不会存在。如果这些是“静态”资产,您可以将它们放在 public 文件夹下,而不是 src

标签: javascript html reactjs


【解决方案1】:

您的文件路径不正确尝试使用 ./assets/weather 给出正确的路径

【讨论】:

    【解决方案2】:

    成功了!!

    const getWeatherIcon = (iconParameter) => {
        const icon = `${iconParameter}.svg`
        return < img src={icon} alt={iconParameter} width='100px' />
      }
    

    <div className="weathericon">
                      {getWeatherIcon(weather.weather[0].main)}//Haze, Clear etc.
                    </div>
    

    文件系统:

    src
    │   App.js
    │   index.css
    │   index.js   
    │
    └───assets
    │   └───bg
    │   |   file111.png
    │   |   file112.png
    │
    │        
    public
    │   Clear.svg
    │   Clouds.svg
    │   Rain.svg
    │   Haze.svg
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-04
      • 2021-05-02
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      相关资源
      最近更新 更多