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'设置为黑色,否则将其设置为红色.
如果条件变得复杂,我建议使用函数,以免降低代码的可读性.
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)