Javascript jsx中三元算子的多重条件
黑色是默认颜色,但是如果我想添加第三个条件呢Javascript jsx中三元算子的多重条件,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,黑色是默认颜色,但是如果我想添加第三个条件呢 状态可以是“已批准”、“已拒绝”、“待决”或更多。您可以执行以下操作: <div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}> </div> 这意味着如果status====“approved”将背景色设置为蓝色,如果status===“pending”将其设置为黑色,否则将其设置为红色。使用多个三元运算符不是一个好主意,最好
状态可以是“已批准”、“已拒绝”、“待决”或更多。您可以执行以下操作:
<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}>
</div>
这意味着如果
status====“approved”
将背景色设置为蓝色,如果status===“pending”
将其设置为黑色,否则将其设置为红色。使用多个三元运算符不是一个好主意,最好使用一个函数,并将if-else条件放入其中,然后从渲染调用该函数。它有助于使渲染部分干净和简短
像这样:
<div style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'pending' ? 'black' : 'red'}}>
</div>
_风格(状态){
如果(状态=‘已批准’)
返回“蓝色”;
else if(状态=‘待定’)
返回“黑色”;
否则返回“红色”;
}
我会单独处理,因为将来可能会出现其他类型的状态
<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(状态){
如果(状态==‘已批准’){
返回“蓝色”
}
else if(状态==‘待定’){
返回“黑色”
}否则{
返回“红色”
}
}
代码变得更容易理解和推理 如果您的情况变得复杂,我建议您使用函数,以免降低代码的可读性
const getBackgroundColor(status) {
if (status === 'approved') {
return 'blue'
}
else if (status === 'pending') {
return 'black'
} else {
return 'red'
}
}
<div style={{'backgroundColor': getBackgroundColor(status) }}>
</div>
getBackgroundColor(状态){
如果(状态==‘已批准’){
返回“蓝色”;
}
如果(状态=='pending'){
返回“红色”;
}
返回“黑色”;
}
render(){
// ...
返回(
);
}
要链接三元操作,您需要添加另一个三元运算符,以便在不满足条件时返回,例如:
a===true?a:b
在b
中添加一个新的三元运算符,如下所示:
a===true?a:b==对吗?b:c
奖金:
当您只是检查null/undefined/false时,可以使用管道操作符,例如:
var x=a!==无效的a:b代码>
可简化为:
var x=a | | b代码>
管道操作符可以像三元操作符一样无限链接。还有另一种方法,可以使用可读性更强、更清晰的代码样式来实现。我们可以用object-literal替换三元运算符,并使用它代替嵌套三元运算符,就像这样
getBackgroundColor(status) {
if (status === 'approved') {
return 'blue';
}
if (status === 'pending') {
return 'red';
}
return 'black';
}
render() {
// ...
return (
<div style={{ 'backgroundColor': this.getBackgroundColor(status) }}></div>
);
}
函数getBackgroundColor(状态){
const backgroundColorByStatus={
批准:“蓝色”,
待定:'黑色',
默认值:“红色”,
}
返回backgroundColorByStatus[状态]| | backgroundColorByStatus['default']
}
//在下面某处
花式跳水
使用这种方法,您可以拥有多种颜色,代码仍然清晰易读:)
希望它能有所帮助。真的,如果你有两个可能的结果,你应该只使用三元。您可以“链接”三元组以添加更多可能的结果,但它往往会很快变得混乱。只需使用if
。不要在JSX中处理所有问题。我将编写一个函数,根据状态返回正确的颜色,并从JSX调用该函数。第二个条件可能重复三元运算符的工作方式?
function getBackgroundColor(status){
const backgroundColorByStatus = {
approved: 'blue',
pending: 'black',
default: 'red',
}
return backgroundColorByStatus[status] || backgroundColorByStatus['default']
}
// somewhere below
<div style={{'backgroundColor': getBackgroundColor(status)}}>fancy div</div>