[英]Conditionally assign the value of a variable to an object's property that may be null
[英]Assign className conditionally based on source object property
我在 React function 中有一個條件,它有條件地添加了 CSS class。
當我在所有其他值中添加默認值時,狀態將獲得“isUnPublished”class 而不是獲得“默認”class..
如果我在前 2 個值中省略默認值,它將顯示最后一個值的默認 class。
代碼:
狀態.JS:
const StatusIndicator = (props) => {
const articleStatus = [
{
id: 1,
name: "published",
isPublished: false
},
{
id: 2,
name: "unpublished",
isUnPublished: false
},
{
id: 3,
name: "draft",
isApproved: false
}
]
return (
<div className={classes.root}>
{articleStatus.map(status => <span key={status.id}
className={
status.isPublished ? 'published' : 'default' ||
status.isUnPublished ? 'unpublished' : 'default'||
status.isApproved? 'draft' : 'default'
}> </span>)}
</div>
)
}
export default StatusIndicator;
CSS:
.published {
background: rgb(75, 210, 143);
display: flex;
width: 10px;
height: 10px;
border-radius: 50%;
}
.unpublished {
background: rgb(255, 77, 77);
display: flex;
width: 10px;
height: 10px;
border-radius: 50%;
}
.draft {
background: rgb(255, 204, 103);
display: flex;
width: 10px;
height: 10px;
border-radius: 50%;
}
.default {
height: 10px;
display: flex;
width: 10px;
background: #c1c1c1;
border-radius: 50%;
}
您似乎在某種程度上濫用了三元運算符。 我想, 它必須是一些東西,比如:
className={
status.isPublished ? 'published' :
status.isUnPublished ? 'unpublished' :
status.isApproved? 'draft' : 'default'
}
為了更好的可讀性,您可以將 class 名稱計算移到單獨的方法中
const getClassName = status => {
switch (true) {
case status.isPublished:
return 'published';
case status.isUnPublished:
return 'unpublished';
case status.isApproved:
return 'draft';
default:
return 'default';
}
};
...
return (
<div className={classes.root}>
{articleStatus.map(status => (
<span key={status.id} className={getClassName(status)}></span>
))}
</div>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.