我有一种情况,我需要根据多个条件向 div 元素添加一个类,这里我使用三元运算符进行嵌套
<div className={
typeof this.state.weather.main !== "undefined"
? this.state.weather.main.temp > 16
? "app warm"
: "app cold"
: "app"
}
>
我想要一些类似的东西,
if(this.state.weather.main.temp < 16){
//add "app cold" class
} else if(this.state.weather.main.temp > 16){
//add "app warm" class
} else if (this.state.weather.main.temp > 35){
//add "app hot" class
} else if(this.state.weather.main.temp > 50){
//add "app extreme" class
}
.....
等等
我建议您将该逻辑移出JSX
并在您的组件中创建一个方法,该方法将返回适当的样式类。
class App extends React.Component {
constructor(props) {
// ...
}
getElementStyles = () => {
const { temp } = this.state.weather.main;
if (temp < 16) {
return "app cold";
}
if (temp > 16) {
return "app warm";
}
if (temp > 35) {
return "app hot";
}
return "app";
}
render() {
const classes = this.getElementStyles();
return (
<div className={classes}>
...
</div>
)
}
}
另外,我想提出的一个建议是,您需要查看温度范围,而不是查看是否temp
小于或大于某个数字,否则您将无法获得准确的结果。
getElementStyles = () => {
const { temp } = this.state.weather.main;
if (temp >= 0 && temp < 16) {
return "app cold";
}
if (temp >= 16 && temp < 35) {
return "app warm";
}
if (temp >= 35 && temp < 50) {
return "app hot";
}
if (temp >= 50) {
return "app extreme";
}
return "app";
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句