【问题标题】:Change class depending on API response [closed]根据 API 响应更改类 [关闭]
【发布时间】:2021-03-31 23:24:15
【问题描述】:

我想根据 API 的响应将类更改为我的 div 容器。更具体地说,如果 API 返回超过 0 度的温度,我希望背景为红色,如果低于我希望它为蓝色。 (稍后将是图像,但现在是颜色。)

我想检查一下celsius={this.state.celsius}

使用所有代码更新

import './App.css';
import React from 'react';
import Header from './components/Header';
import Footer from './components/Footer';
import Search from './components/Search';
import Form from './components/Form';

const API_KEY = '*********************'

class App extends React.Component {
  constructor(){
    super();
    this.state = {
      city: undefined,
      celsius: undefined,
      wind: undefined,
      feelsLike: undefined
    };
  }
     
evenDeagree(temp){
  let cell = Math.floor(temp)
  return cell;
}   

getWeather = async (e) => {   
  try {
  e.preventDefault();
   "city."
  const city= e.target.elements.city.value;
 datan.
  if(city){    

    const api_call = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`
    );
    reponse
    const response = await api_call.json();
    console.log(response)

    this.setState({
      city: "City: " + `${response.name}`,
      celsius: "Current Degree: " + this.evenDeagree(response.main.temp) + "°C",
      wind: "Wind m/s: " + this.evenDeagree(response.wind.speed),
      feelsLike: "Känns som: " + this.evenDeagree(response.main.feels_like) + "°C"

      });
  }   
} 

catch(error) {
  document.getElementById("errMessage").innerHTML =  "City not found, please try again";
  
}

}

  render(){
    return(
      <div className="App">
      <Header />
      <div className="mainContainer">
      <Form loadweather={this.getWeather}/> 

      <div className={this.state.celsius > 0 ? "red" : "blue"}>
      <Search 
          city={this.state.city} 
          celsius={this.state.celsius}
          wind={this.state.wind}
          feelsLike={this.state.feelsLike}
        />
        </div>

    </div>
      <Footer />
    </div>
    );
  }
}

【问题讨论】:

  • 您希望根据条件将班级设为background-color-redbackground-color-bluebackground-color-standard
  • 您可以在这里使用三元运算符来确定要分配哪个类,例如className={this.state.celsius &gt; 0 ? "red" : "blue"}
  • 是的,虽然我可以在两个不同的类上应用 2 个不同的背景图像,并根据 API 响应的内容切换类,在这种情况下 response.main.temp >= 0。希望这是有道理的。

标签: reactjs api fetch


【解决方案1】:

您可以通过多种方式实现这一点,在 useState 的帮助下,您可以使用默认类设置状态并使用网络请求完成更新类。

或者您可以使用 css modulse 并添加一个类数组并在不满足您的条件时加入另一个类等。

下面是一个示例,可以帮助您了解如何动态传递类名。

代码沙盒 => https://codesandbox.io/s/exciting-gagarin-ugy7d?file=/src/styles.css:0-162

import React, { useEffect, useState } from "react";
import "./styles.css";

const App = () =>
{
  const [className, setClassName] = useState("App");

  useEffect(() => 
  {
    //Fake Api Cal
    setTimeout(() => 
    {
      setClassName("App-New");
    }, 3000);
  }, []);

  return (
    <div className={className}>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

export default App;


/*styles.css*/
.App 
{
  font-family: sans-serif;
  text-align: center;
  background: green
}


.App-New 
{
  font-family: sans-serif;
  text-align: center;
  background: red
}

【讨论】:

  • 感谢您如此明确的回复。但是,我没有使用任何 useEffect,但到目前为止,我在 React 中只使用了 3 天。我敢打赌,当我想在这里做这个或那个时,一个更简单的解决方案是我猜这个条件渲染? :)
  • 如果您发布更多关于如何进行网络请求和存储这些值的代码,这可以帮助我们更好地使用条件样式。
  • 我更新了帖子 :) 干杯。
  • @Niqqo ,您的问题得到答案了吗?还是有问题?
猜你喜欢
  • 2021-10-19
  • 1970-01-01
  • 2021-12-09
  • 2021-09-04
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多