javascript - 如何将温度从摄氏度转换为华氏度?
问题描述
我的天气应用程序几乎完成了,只是无法将我的温度从摄氏温度转换为华氏温度。我制作了一个按钮并使用了一个事件处理程序来查看它是否有效,但是当我获取一个城市的 api 时,它显示了两种转换。此外,当我按下转换按钮时,它会使华氏温度消失(老实说希望这种情况发生但相反,所以它会在点击时弹出)。老实说,这是我需要做的最后一件事。
应用程序.js:
import React, { Component } from "react";
import Greeting from "./Greeting";
const API_key = "dsdfghjkjhgfd";
class App extends Component {
constructor(props) {
super(props);
this.state = {
city: "",
country: undefined,
weather: "",
temp: "",
fahr: true,
};
this.handleChange = this.handleChange.bind(this);
this.handleConvert = this.handleConvert.bind(this);
this.newTemp = this.newTemp.bind(this);
}
newTemp(temp) {
let cell = Math.floor((temp * 9) / 5) + 32;
return cell;
}
calCelsius(temp) {
let cell = Math.floor(temp);
return cell;
}
/*shouldComponentUpdate() {
this.handleConvert();
}*/
handleConvert() {
const { fahr } = this.state;
this.setState({
fahr: true,
});
}
componentDidMount() {
this.handleConvert();
}
handleChange(event) {
const { name, value } = event.target;
this.setState({ [name]: value });
this.handleSubmit = async (e) => {
e.preventDefault();
const city = event.target.value;
fetch(
`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_key}`
)
.then((response) => response.json())
.then((response) => {
console.log(response);
this.setState({
city: `${response.name}`,
country: `${response.sys.country}`,
temp: this.calCelsius(`${response.main.temp}`),
fahr: this.newTemp(`${response.main.temp}`),
weather: `${response.weather[0].main}`,
});
});
};
}
render() {
let date = String(new window.Date());
date = date.slice(0, 15);
return (
<div
className={
typeof this.state.weather != "undefined"
? this.state.temp > 16
? "app hot"
: "app"
: "app"
}
>
<main>
<div className="search-box">
<form onSubmit={this.handleSubmit}>
<input
type="text"
className="search-bar"
placeholder="Enter a city"
name="city"
onChange={this.handleChange}
value={this.state.value}
/>
</form>
</div>
<div>
<div className="location-box">
<div className="location">
{this.state.city},{this.state.country}{" "}
</div>
<div className="date">{date}</div>
<div className="greet">
<Greeting />
</div>
<div className="weather-box">
<div className="temp">{this.state.temp}°C</div>
<div className="fahr">{this.state.fahr}°F</div>
<div className="weather">{this.state.weather}</div>
<button onClick={this.handleConvert}>Convert Temp</button>
</div>
</div>
</div>
</main>
</div>
);
}
}
export default App;
解决方案
您可以通过将任何摄氏度值乘以 9/5 并加上 32 将其转换为华氏度。
例子:
function convertToF(celsius) {
return celsius * 9/5 + 32
}
convertToF(30); // 86
推荐阅读
- openlayers - 通过地图缩放更改图标大小
- css - SCSS:使用网格时出现编译错误:repeat(auto-fit, minmax(260px, 1fr));
- mysql - 寻找最有效的选择查询
- bash - shell中的哈希图样式数组?
- javascript - 运行以下脚本后,只显示一个圆圈。为什么?我该如何解决?
- scala - 为什么我的 sbt 文件夹中同时包含 0.13 和 1.0?
- php - GAE - PHP7 - 如何通过前端控制器传递 GET 参数
- mapbox-gl-js - Tippecanoe 生成的 pbf 存储在 s3 上,在 mapbox-gl 上可视化
- firebase - 如何验证当前 FirebaseUser 是否存在?
- github - 从 GitHub 链接到 NuGet