我有一个可在天气应用程序中将温度从摄氏温度更改为华氏温度的开关。代码如下:
import React, { Component } from "react";
class Temperature extends Component {
state = {
unit: "metrics"
};
imperial = () => {
this.setState({
unit: "imperial",
imperialTemp: Math.round(this.props.temp * (9 / 5) + 32),
imperialMin: Math.round(this.props.temp1 * (9 / 5) + 32),
imperialMax: Math.round(this.props.temp2 * (9 / 5) + 32)
});
};
metrics = () => {
this.setState({
unit: "metrics"
});
};
render() {
if (this.state.unit === "metrics") {
return (
<div>
<div className="temp">
{this.props.temp}ºC |
<span className="fahrenheit" onClick={this.imperial}>
°F
</span>
</div>
<div className="row">
<div className="col">
<div className="min-max">
{this.props.temp1}ºC |
<span className="fahrenheit" onClick={this.imperial}>
°F
</span>{" "}
| {this.props.temp2}ºC |
<span className="fahrenheit" onClick={this.imperial}>
°F
</span>
</div>
</div>
</div>
</div>
);
} else {
return (
<div>
<div className="temp">
{this.state.imperialTemp}
<span className="celsius" onClick={this.metrics}>
ºC |
</span>
ºF
</div>
<div className="row">
<div className="col">
<div className="min-max">
{this.state.imperialMin}
<span className="celsius" onClick={this.metrics}>
ºC |
</span>
ºF | {this.state.imperialMax}
<span className="celsius" onClick={this.metrics}>
ºC |
</span>
ºF
</div>
</div>
</div>
</div>
);
}
}
}
export default Temperature;
由于我仅在每种条件下添加一条当前温度线和一条最小/最大线,为什么会发生这种情况?为什么每个显示两个? ºC是怎么回事?有什么建议吗?预先谢谢你。
更新:
我两次渲染了Temperature组件,这就是为什么第一张图像正在发生的原因。现在它愉快地显示了此
然而,与CS的混乱仍然存在:
帮助!
答案 0 :(得分:1)
根据您发布的代码,看来temp1
和temp2
道具不是数字,并且您两次渲染了Temperature
组件。
但是,如果不查看父组件,很难知道。与渲染Temperature
的父对象一起更新代码会有所帮助。
问题°C
看起来像celsius
类的问题,如果您发布该代码也将有所帮助。
注意:如果您以状态切换数据,而不是有条件地呈现2个几乎相同的UI,则可以简化此代码。像这样:
class Temperature extends Component {
state = {
unit: "metrics",
tempClass: "celsius",
temp: this.props.initialTemp,
tempMin: this.props.initialTemp1,
tempMax: this.props.initialTemp2
};
toggleUnits = () => {
this.setState(prevState => prevState.unit === "metrics" ? {
unit: "imperial",
tempClass: "fahrenheit",
temp: this.toFahrenheit(prevState.temp),
tempMin: this.toFahrenheit(prevState.tempMin),
tempMax: this.toFahrenheit(prevState.tempMax)
} : {
unit: "metrics",
tempClass: "celsius",
temp: this.toCelsius(prevState.temp),
tempMin: this.toCelsius(prevState.tempMin),
tempMax: this.toCelsius(prevState.tempMax)
});
};
toFahrenheit = temp => Math.round(temp * (9 / 5) + 32)
toCelsius = temp => Math.round((temp - 32) * (5 / 9))
render() {
const { temp, tempClass, tempMin, tempMax } = this.state;
return (
<div>
<div className="temp">
{temp}ºC |
<span className={tempClass} onClick={this.toggleUnits}>
°F
</span>
</div>
<div className="row">
<div className="col">
<div className="min-max">
{tempMin}ºC |
<span className={tempClass} onClick={this.toggleUnits}>
°F
</span>{" "}
| {tempMax}ºC |
<span className={tempClass} onClick={this.toggleUnits}>
°F
</span>
</div>
</div>
</div>
</div>
);
}
}