我试图从开放的天气地图api中显示天气图标,但我不完全确定如何做到这一点,这里是文档https://openweathermap.org/weather-conditions ..我传递的weather.icon就像它在文档中写的但是由于某些原因它不能工作,有人可以告诉我我做错了什么吗?谢谢
app.js
class App extends React.Component {
state = {
temperature: undefined,
city: undefined,
country: undefined,
pressure: undefined,
humidity: undefined,
description: undefined,
rain:undefined,
icon:undefined,
error: undefined
}
handlenum1Change (evt) {
let temp = (evt.target.value);
}
getWeather = async (e) => {
e.preventDefault();
const city = e.target.city.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
const data = await api_call.json();
console.log(data)
if (city) {
this.setState({
temperature: data.main.temp,
city: data.name,
icon: data.weather.icon,
rain: data.rain,
pressure: data.main.pressure,
humidity: data.main.humidity,
description: data.weather[0].description,
error: ""
});
} else {
this.setState({
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
pressure:undefined,
rain : undefined,
error: "Please enter the values."
});
}
}
render() {
return (
<div>
<div className="wrapper">
<div className="main">
<div className="container">
<div className="row">
<div className="col-xs-5 title-container">
</div>
<div className="col-xs-7 form-container">
<form onSubmit={this.getWeather} >
<input type="text" name="city" onChange={this.handlenum1Change} placeholder="City..."/>
<button>Get Weather</button>
</form>
<Weather
temperature={this.state.temperature}
humidity={this.state.humidity}
city={this.state.city}
pressure={this.state.pressure}
description={this.state.description}
rain={this.state.rain}
icon={this.state.icon}
error={this.state.error}
/>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
};
export default App;
weather.js
import React from 'react';
import PropTypes from 'prop-types';
const Weather = props =>
<div>
<p>{props.city}</p>
<p> humidity {props.humidity }</p>
<p> {props.description} </p>
<p> temperature {props.temperature}</p>
<p> atmospheric pressure : {props.pressure}</p>
<p> atmospheric pressure : {props.rain}</p>
<img className="img-fluid" src={props.icon} />
</div>
export default Weather;
答案 0 :(得分:1)
根据weather.js中的代码
<img src ={`http://openweathermap.org/img/w/${this.props.icon}.png`} alt="wthr img" />
它将显示天气图标...即
import React, { Component } from 'react';
class Weather extends Component {
render() {
return (
<div>
<p>WeatherNow:
<img src ={`http://openweathermap.org/img/w/${this.props.icon}.png`}
alt="wthr img" />
</p>
</div>
);
}
}
export default Weather;
答案 1 :(得分:0)
您必须在<img>
的src属性中进行更改。
如Weathermap api中所示,您必须通过http://openweathermap.org/img/w/10d.png请求图标。
将10d.png
替换为props.icon+'.png'
。它会起作用。
答案 2 :(得分:0)
为了显示图标,您需要使用URL而不仅仅是图标值。像这样的东西
API返回的值是&lt; 09d&#39;因此,您必须使用字符串url附加URL,以便为天气api url添加图像和图像扩展名。
{http://openweathermap.org/img/w/${props.icon}.png
}
您将默认值设置为undefined,这是不正确的。
请使用适当的值,例如
state = { 温度:&#39;&#39;, 城市:&#39;&#39; }