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

标签 reactjs background-image openweathermap weather-api

我是 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 调用的函数。但是图像没有显示(img 1),但要将 img 作为背景,我会调用 <Background>从我的 App 功能 (img 2 ),但在这种情况下,我将无法访问输入城市的真实图标值。我应该提到我在“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>
    )
}

搜索.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"
    />
  )
}

关于reactjs - 将背景与用户当前的天气状况相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71950959/

相关文章:

reactjs - 从 React Components 生成 PDF 文件

javascript - 构建 react 应用程序的版本,提供指向 CSS 和 JS 文件的错误链接

html - 剪下透明三 Angular 形的图像

wordpress - 如何使背景图像加载更快

python - urllib 无法处理 api 请求

javascript - 小屏幕的 scaleY 属性未正确维护

javascript - ReactJS - 单击单选按钮时动态更改组件的颜色

html - 更改背景图像重复文件

java - 如何在android中的OpenWeatherMap api中更改描述语言

JSON 返回 "\"(Lambda)