我想将温度从摄氏温度更改为华氏温度(反之亦然),但我还没有找到解决此问题的正确方法,我编写了一个函数来进行摄氏温度到华氏温度的转换,但它引发了错误。所以我需要有人能够打开我的大脑并向我解释这一点哈哈(让我明白我在说什么)。
这是我的代码:https://codepen.io/manAbl/pen/aGymRg?editors=0011
我在评论中添加了以下函数,该函数不起作用:
convertingTemperature() {
const { Fahrenheit, Celcius } = this.state;
this.setState({
Fahrenheit: true,
});
const _Celcius = this.state.weather.weather && this.state.weather.main.temp;
const _Fahrenheit = Math.round(_Celcius * 5 / 9 + 32);
if(Fahrenheit) {
this.setState({ temp: _Fahrenheit })
};
}
我想要做的是将我的状态保持为 bool 值,因此如果华氏度为真,我可以进行转换并调用我的函数,但我认为不起作用的原因是因为我正在提取该值来 self 的天气状态对象,它来 self 的 api 调用。所以我想将该值提取到一个单独的状态,以便我可以用它进行转换。
--- 我想说的是,我希望在点击温度时能够在华氏度和摄氏度之间切换
最佳答案
我更新了您的代码以使用 2 个组件,其中温度以及与温度相关的所有内容都在 WeatherData
组件中定义。温度使用 props 传递给它,并且总是以 Celcius 传递。 (注意!!!)
这里的主要思想是您有两个组件,其中 temp 作为 prop
传递给另一个组件。该组件还处理从 C 到 F 的转换,并且当用户单击范围时,还使用函数 getCorrectTemp()
将 C 转换为 F(该函数还将其格式化为字符串。
注意:记住onClick
事件中的bind
,否则this
上下文将会丢失。
class WeatherData extends React.Component {
constructor(props) {
super(props);
this.state = { isCelcius: true }
}
toggleIsCelcius() {
this.setState({isCelcius: !this.state.isCelcius});
}
getCorrectTemp(temp, isCelcius) {
if(this.state.isCelcius) return `${this.props.tempCelcius} C`;
return `${(this.props.tempCelcius*9/5)+32} F`;
}
render() {
const { main,name,icon,country,tempCelcius } = this.props;
if(tempCelcius) {
const tempFormatted = this.getCorrectTemp(tempCelcius, this.state.isCelcius);
return (
<div className='app-wrapper'>
<p>{name},{country}</p>
<small>{main}</small>
<span onClick={this.toggleIsCelcius.bind(this)}>{tempFormatted}</span>
<img src={icon} alt=''/>
</div>
);
} else {
return <div className='app-wrapper'>Loading ...</div>
}
}
}
我还添加了一个加载状态,但如果您不需要,可以将其删除。只需记住处理尚未从服务器接收到临时值的状态即可。
关于javascript - 基于状态的函数执行无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201712/