将背景与用户当前的天气状况相匹配

Match background with users current weather conditions

我是 React 的新手,正在努力学习,但遇到了这个无法解决的问题。我已经开发了一个天气应用程序,我仍在努力,但此刻我被困了 3 天,试图让背景图像根据用户的天气状况而变化。我已经尝试使用来自 openweather API 的图标。我使用相同的方法获取图标(来自我的文件夹的图像)以匹配用户的天气条件。

   import React from "react";
   export default function Background(props) {
const codeMapping = {
"01d": "clear-sky-day",
"01n": "clear-sky-night",
"02d": "cloudy-day",
"02n": "cloudy-night",
"03d": "cloudy-day",
"03n": "cloudy-night",
"04d": "cloudy-day",
"04n": "cloudy-night",
"09d": "shower-rain-day",
"09n": "shower-rain-night",
"10d": "rain-day",
"10n": "rain-night",
"11d": "thunderstorm-day",
"11n": "thunderstorm-night",
"13d": "snow-day",
"13n": "snow-night",
"50d": "fog-day",
"50n": "fog-night",
};
let name = codeMapping[props.code];
return (
<img
  className="background"
  src={`background/${name}.jpg`}
  alt={props.alt}
  size="cover"
/>
);
}

所以...为了获得用户输入城市的“图标”,我必须从处理提交表单的函数“搜索”中调用 "<Background cod={weatherData.icon} alt={weatherData.description} />" 和 运行 api 要求输入城市。但是图像没有显示(img1), but to have the img as a background I would call <Background> from my App function(img2),但在这种情况下,我将无法从输入城市访问真实的图标值。我应该提到我在“src”中有一个名为 background 的文件夹,图像名称与映射中的代码名称相匹配。 提前致谢!

current preview of my app
how I see in other documentation I should set a background

您可以将 Search.js 中的 code 作为状态传递。

App.js

const codeMapping = {
    "01d": "clear-sky-day",
    "01n": "clear-sky-night",
};

export const App = () => {

    const [code, setCode] = useState(null) // <-- We'll update this from Search.js
    const [backgroundImage, setBackgroundImage] = useState("")

    useEffect(() => {
        // Set background value based on the code
        setBackgroundImage(codeMapping[`${code}`]) 
    }, [code]); // <-- useEffect will run everytime the code changes

    return (
        <div style={{
            height: '100px', 
            width: '100px',
            backgroundImage: `${backgroundImage || "defaultBackgroundImage"}`
        }}>
          <Search setCode={setCode} />
        </div>
    )
}

Search.js

import { WeatherContext } from './App';

export const Search = ({ setCode }) => {
  
  const handleClick = (apiResponse) => {
    // Some API call returning the actual code value here //
    setCode(apiResponse)
  }
  
  return (
    <input
      onClick={() => handleClick("01n")}
      type="button"
      value="Change city"
    />
  )
}