ReactJS将动态类添加到手动类名称

我需要将动态类添加到常规类列表中,但是不知道如何(我正在使用babel),如下所示:

<div className="wrapper searchDiv {this.state.something}">
...
</div>

有任何想法吗?

西门GO村村2020/03/11 15:35:11
getBadgeClasses() {
    let classes = "badge m-2 ";
    classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
    return classes;
}

<span className={this.getBadgeClasses()}>Total Count</span>
GOMandy2020/03/11 15:35:11

尝试使用钩子:

        const [dynamicClasses, setDynamicClasses] = React.useState([
    "dynamicClass1", "dynamicClass2
]);

并将其添加到className属性中:

<div className=`wrapper searchDiv ${[...dynamicClasses]}`>
...
</div>

添加类:

    const addClass = newClass => {
       setDynamicClasses([...dynamicClasses, newClass])
    }

删除班级:

        const deleteClass= classToDelete => {

           setDynamicClasses(dynamicClasses.filter(class = > {
             class !== classToDelete
           }));

        }
阳光西里小哥2020/03/11 15:35:11

一个简单的可能语法为:

<div className={`wrapper searchDiv ${this.state.something}`}>
LEY乐2020/03/11 15:35:11

这是Dynamic className的最佳选择,就像我们在Javascript中那样进行一些串联。

     className={
        "badge " +
        (this.state.value ? "badge-primary " : "badge-danger ") +
        " m-4"
      }