jsx中三元运算符的多重条件

Jen*_*Mok 9 javascript jsx reactjs

<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}>
</div>
Run Code Online (Sandbox Code Playgroud)

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

状态可以"已批准","已拒绝","待处理"或更多.

Pau*_*ald 11

您可以执行以下操作:

<div style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'pending' ? 'black' : 'red'}}>
</div>
Run Code Online (Sandbox Code Playgroud)

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


Gha*_*chi 8

如果条件变得复杂,我建议使用函数,以免降低代码的可读性.

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

render() {
    // ...

    return (
        <div style={{ 'backgroundColor': this.getBackgroundColor(status) }}></div>
    );
}
Run Code Online (Sandbox Code Playgroud)

  • 像其他一些答案一样,链接三元语句绝对是不可读的,也是一种可怕的做法。这个解决方案很明确,应该是公认的答案。 (5认同)