JSX中三元运算符中的多个条件

24
<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}>
</div>

黑色是默认颜色,但如果我想增加第三个条件怎么办?

状态可以是“已批准”、“已拒绝”、“待定”或更多。


2
实际上,只有当你有两个可能的结果时才应该使用三元运算符。你可以通过“链接”多个三元运算符来增加更多的可能结果,但这往往会变得非常混乱。最好直接使用“if”语句。 - Carcigenicate
1
不要全部在JSX中处理。我会编写一个函数,根据状态返回正确的颜色,并从JSX中调用该函数。 - Andy
可能是[多个三元运算符]的重复问题(https://dev59.com/_Wsz5IYBdhLWcg3wpZdF)。 - bennygenel
在React/JSX中,如果有一个内联的“switch”选项,就像if/elseif/else一样,那将是很好的。 - Ben in CA
9个回答

37

如果您的条件变得复杂,我建议使用函数来保持代码的可读性。

getBackgroundColor(status) {
    if (status === 'approved') {
        return 'blue';
    }
    if (status === 'pending') {
        return 'red';
    }
    return 'black';
}

render() {
    // ...

    return (
        <div style={{ 'backgroundColor': this.getBackgroundColor(status) }}></div>
    );
}

5
像其他答案所建议的链接三元语句绝对是不可读且糟糕的做法。这个解决方案是清晰的,应该被接受作为答案。 - Cobie Fisher
1
这是一个非常好的练习,谢谢你的分享! - KYin

36
你可以按照以下步骤操作:
<div style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'pending' ? 'black' : 'red'}}>
</div>

这意味着如果 status === 'approved',则将背景颜色设置为蓝色,如果 status === 'pending',则将其设置为黑色,否则将其设置为红色。


4
要链式使用三元操作符,您需要在未满足条件时添加另一个要返回的三元操作符,例如:
a === true ? a : b
在b的位置上,您可以添加一个新的三元操作符,如下所示:
a === true ? a : b === true ? b : c
奖励:
当您只检查null / undefined / false时,可以使用管道运算符,例如:
var x = a!== null?a:b;
可以简化为:
var x = a || b;
管道运算符可以像三元运算符一样无限地链接。

在第二个条件上,那个三元运算符是如何工作的? - Shweta

2

JSX和JS中三元运算符的多条件语句

style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'cancel' ? 'red' : 'green'}}

2

有另一种更易读且更清晰的代码风格来完成它。我们可以用对象字面量替换三元运算符,并使用 this 来代替嵌套的三元运算符,如下所示:

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>

采用这种方法,您可以拥有多种颜色,并且代码仍然干净并易于阅读 :)

希望它能有所帮助。


1

使用多个三元运算符并不是一个好主意,最好使用一个函数并在其中放置if-else条件,并从render中调用该函数。这有助于使渲染部分变得干净和简短。

像这样:

<div style={{'backgroundColor': this._style(status)}}></div>

_style(status){
    if(status == 'approved')
        return 'blue';
    else if(status == 'pending')
        return 'black';
    else return 'red';
}

1

我会将其单独处理,因为未来可能会出现其他类型的状态。

const getBackgroundColor(status) {
  if (status === 'approved') {
    return 'blue'
  }
  else if (status === 'pending') {
    return 'black'
  } else {
    return 'red'
  }
}

<div style={{'backgroundColor': getBackgroundColor(status) }}>
</div>

代码变得更易于理解和推理。


0

我不会使用三目运算符,因为它难以阅读。为什么不将状态和相关颜色存储在一个对象中,然后只需引用该对象呢?

const colors = {approved:"blue", rejected:"red"};


<div style={{'backgroundColor':status in colors ? colors[status] : "black"}}>
</div>

哎呀,我没意识到这个帖子已经很老了。


-1

在 render 中,您可以创建一个空数组变量。如下所示,您可以应用嵌套样式。此外,您也不需要嵌套三元运算符。

let styleValue = [];
if(status === 'approved') {
  styleValue.push({backgroundColor:'blue'})
} else {
  styleValue.push({backgroundColor:'black'})
}

<div style={styleValue}>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接