我更新了您的代码以使用2个组件,其中温度以及与温度相关的所有内容都在
WeatherData
组成部分温度通过道具传递给它,并且始终通过
塞尔修斯
(注意!!!)
My CodePen
这里的主要思想是有两个组件,其中温度作为
prop
到另一个组件。该组件还处理从C到F的转换,当用户单击span时,还使用函数将C转换为F
getCorrectTemp()
(它还将其格式化为字符串。
注意:记住
bind
在
onClick
事件,否则
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>
}
}
}
我还添加了一个加载状态,但如果不需要,可以将其删除。只需记住处理尚未从服务器接收到temp的状态。