<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}>
</div>
黑色是默认颜色,但如果我想增加第三个条件怎么办?
状态可以是“已批准”、“已拒绝”、“待定”或更多。
<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}>
</div>
黑色是默认颜色,但如果我想增加第三个条件怎么办?
状态可以是“已批准”、“已拒绝”、“待定”或更多。
如果您的条件变得复杂,我建议使用函数来保持代码的可读性。
getBackgroundColor(status) {
if (status === 'approved') {
return 'blue';
}
if (status === 'pending') {
return 'red';
}
return 'black';
}
render() {
// ...
return (
<div style={{ 'backgroundColor': this.getBackgroundColor(status) }}></div>
);
}
<div style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'pending' ? 'black' : 'red'}}>
</div>
这意味着如果 status === 'approved'
,则将背景颜色设置为蓝色,如果 status === 'pending'
,则将其设置为黑色,否则将其设置为红色。
JSX和JS中三元运算符的多条件语句
style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'cancel' ? 'red' : 'green'}}
有另一种更易读且更清晰的代码风格来完成它。我们可以用对象字面量替换三元运算符,并使用 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>
采用这种方法,您可以拥有多种颜色,并且代码仍然干净并易于阅读 :)
希望它能有所帮助。
使用多个三元运算符并不是一个好主意,最好使用一个函数并在其中放置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';
}
我会将其单独处理,因为未来可能会出现其他类型的状态。
const getBackgroundColor(status) {
if (status === 'approved') {
return 'blue'
}
else if (status === 'pending') {
return 'black'
} else {
return 'red'
}
}
<div style={{'backgroundColor': getBackgroundColor(status) }}>
</div>
代码变得更易于理解和推理。
我不会使用三目运算符,因为它难以阅读。为什么不将状态和相关颜色存储在一个对象中,然后只需引用该对象呢?
const colors = {approved:"blue", rejected:"red"};
<div style={{'backgroundColor':status in colors ? colors[status] : "black"}}>
</div>
哎呀,我没意识到这个帖子已经很老了。
在 render 中,您可以创建一个空数组变量。如下所示,您可以应用嵌套样式。此外,您也不需要嵌套三元运算符。
let styleValue = [];
if(status === 'approved') {
styleValue.push({backgroundColor:'blue'})
} else {
styleValue.push({backgroundColor:'black'})
}
<div style={styleValue}>
</div>