猿问

根据源对象属性有条件地分配 className

我在一个有条件地添加 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%;

}


侃侃尔雅
浏览 79回答 2
2回答

holdtom

您似乎有点误用三元运算符。我想,它必须是这样的:className={&nbsp;&nbsp; &nbsp; status.isPublished ? 'published' :&nbsp; &nbsp; status.isUnPublished ? 'unpublished' :&nbsp;&nbsp; &nbsp; status.isApproved? 'draft' : 'default'}

烙印99

为了更好的可读性,您可以将类名计算移动到一个单独的方法中const getClassName = status => {&nbsp; &nbsp; switch (true) {&nbsp; &nbsp; &nbsp; &nbsp; case status.isPublished:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 'published';&nbsp; &nbsp; &nbsp; &nbsp; case status.isUnPublished:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 'unpublished';&nbsp; &nbsp; &nbsp; &nbsp; case status.isApproved:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 'draft';&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 'default';&nbsp; &nbsp; }};...return (&nbsp; &nbsp; <div className={classes.root}>&nbsp; &nbsp; &nbsp; &nbsp; {articleStatus.map(status => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span key={status.id} className={getClassName(status)}></span>&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </div>);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答