【发布时间】:2020-01-25 16:11:56
【问题描述】:
我编写了一个 if 语句,它旨在根据两个布尔变量(活动和确认)返回某种颜色。然而,由于具有 Java 背景并且对 ReactJs 和 JSX 不熟悉,我发现这项任务比我觉得需要的要困难得多。 这个 if 语句只返回橙色。我无法理解 && 运算符的工作原理。
目标:如果激活和确认都为真,我想将图标设置为橙色。如果活动为真但确认为假,我想将图标设置为红色。如果活动为假但确认为真,我想将图标设置为绿色。如果活动和确认都为假,则图标将为灰色。
这是我的代码:
//Mapping Json-object
const active = data.Status.map(status => status.active);
const acknowledged = data.Status.map(status => status.acknowledged);
//Method called from component
function bellStatus() {
if(active && acknowledged) {
return {color: "#ff893d", marginRight: "10px"} //orange
}else if(active && !acknowledged) {
return {color: "#fe4242", marginRight: "10px"} //red
}else if(!active && acknowledged) {
return {color: "#5ab65a", marginRight: "10px"} //green
}else {
return {color: "#acacac", marginRight: "10px"} //grey
}
}
//Component in return
<FontAwesomeIcon icon="bell" style={bellStatus()} />
//Json
{
"id": "1",
"Status": [{
"active": true,
"acknowledged": false
}]
},
{
"id": "2",
"Status": [{
"active": false,
"acknowledged": false
}]
},
{
"id": "3",
"Status": [{
"active": true,
"acknowledged": false
}]
}
为什么我会遇到这个问题,这将如何“翻译”成 JSX/ES6?变量显示正确的值,但 if 语句显然是错误的。
【问题讨论】:
-
能贴出完整的代码吗?
-
&&表示如果两个操作数都是true,那么它将是true。如果它返回橙色,这意味着active和acknowledged都是true。完整的代码肯定会有所帮助。 -
map 返回布尔值列表
-
@IshanJoshi 我知道确实如此......这不是这里的问题。问题在于语法。
标签: reactjs