2017-09-25 54 views
1
<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}> 
</div> 

黑色是默認顏色但如果我想添加第三個條件?三元運算符在jsx中的多個條件

狀態可以是「批准」,「拒絕」,「未決」或更多。

+2

真的,你應該只使用三元,如果你有2個可能的結果。你可以「鏈接」三元組來增加更多可能的結果,但它往往會變得雜亂無章。只需使用「if」即可。 – Carcigenicate

+1

不要在JSX中處理這一切。我會寫一個函數,根據狀態返回正確的顏色,並從JSX中調用函數。 – Andy

+0

[Multiple Ternary Operators]的可能重複(https://stackoverflow.com/questions/7757549/multiple-ternary-operators) – bennygenel

回答

2

你可以做到以下幾點:

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

使用多個三元運營商是不是一個好主意,最好使用功能,並把如果其他條件,內部的,並呼籲從渲染功能。它可以幫助您使渲染部分變得乾淨而簡潔。

像這樣:

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

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

我會單獨處理它與其他類型的狀態可能會在未來出現。

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

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

代碼變得更容易理解和推理。

4

我會建議使用函數,如果您的條件變得複雜,不會降低您的代碼可讀性。

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

render() { 
    // ... 

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

要你需要添加當條件不滿足要返回另一個三元運營商,例如連鎖三元操作:

a === true ? a : b

在地方的b您將添加一個新的三元運營商,像這樣:

a === true ? a : b === true ? b : c

獎勵:

當你只是檢查空/未定義/假,你可以使用管道運營商,比如這個:

var x = a !== null ? a : b;

可以簡化爲:

var x = a || b;

管道運營商可以像三元運營商一樣無限鏈接。