三元运算符在jsx中的多个条件
问题描述:
<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}>
</div>
黑色是默认颜色但如果我想添加第三个条件?三元运算符在jsx中的多个条件
状态可以是“批准”,“拒绝”,“未决”或更多。
答
你可以做到以下几点:
<div style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'pending' ? 'black' : 'red'}}>
</div>
答
使用多个三元运营商是不是一个好主意,最好使用功能,并把如果其他条件,内部的,并呼吁从渲染功能。它可以帮助您使渲染部分变得干净而简洁。
像这样:
<div style={{'backgroundColor': this._style(status)}}></div>
_style(status){
if(status == 'approved')
return 'blue';
else if(status == 'pending')
return 'black';
else return 'red';
}
答
我会单独处理它与其他类型的状态可能会在未来出现。
const getBackgroundColor(status) {
if (status === 'approved') {
return 'blue'
}
else if (status === 'pending') {
return 'black'
} else {
return 'red'
}
}
<div style={{'backgroundColor': getBackgroundColor(status) }}>
</div>
代码变得更容易理解和推理。
答
我会建议使用函数,如果您的条件变得复杂,不会降低您的代码可读性。
getBackgroundColor(status) {
if (status === 'approved') {
return 'blue';
}
if (status === 'pending') {
return 'red';
}
return 'black';
}
render() {
// ...
return (
<div style={{ 'backgroundColor': this.getBackgroundColor(status) }}></div>
);
}
答
要你需要添加当条件不满足要返回另一个三元运营商,例如连锁三元操作:
a === true ? a : b
在地方的b
您将添加一个新的三元运营商,像这样:
a === true ? a : b === true ? b : c
奖励:
当你只是检查空/未定义/假,你可以使用管道运营商,比如这个:
var x = a !== null ? a : b;
可以简化为:
var x = a || b;
管道运营商可以像三元运营商一样无限链接。
真的,你应该只使用三元,如果你有2个可能的结果。你可以“链接”三元组来增加更多可能的结果,但它往往会变得杂乱无章。只需使用“if”即可。 – Carcigenicate
不要在JSX中处理这一切。我会写一个函数,根据状态返回正确的颜色,并从JSX中调用函数。 – Andy
[Multiple Ternary Operators]的可能重复(https://*.com/questions/7757549/multiple-ternary-operators) – bennygenel