我在一个有条件地添加 CSS 类的 React 函数中有一个条件。当我在所有其他值中添加默认值时,状态是获取“isUnPublished”类而不是获取“默认”类。如果我在前 2 个值中省略默认值,它会显示最后一个值的默认类。代码:状态.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%;}
2 回答
烙印99
TA贡献1829条经验 获得超13个赞
为了更好的可读性,您可以将类名计算移动到一个单独的方法中
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>
);
添加回答
举报
0/150
提交
取消