我需要添加一个动态类到常规类的列表,但不知道如何(我使用babel),类似这样的东西:

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

什么好主意吗?


当前回答

如果你需要根据状态条件显示的样式名,我更喜欢使用这种结构:

<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>

其他回答

一个简单的语法是:

<div className={`wrapper searchDiv ${this.state.something}`}>

如果你需要根据状态条件显示的样式名,我更喜欢使用这种结构:

<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>
className={css(styles.mainDiv, 'subContainer')}

这个解决方案在React SPFx中进行了尝试和测试。

同时添加import语句:

import { css } from 'office-ui-fabric-react/lib/Utilities';

你可以使用这个npm包。它处理所有事情,并基于变量或函数为静态类和动态类提供选项。

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />

简单地在数组中组合类名,删除空值并连接到字符串中。

<div className={["wrapper", "searchDiv",, undefined, null, this.state.something].filter((e) => e).join(" ")}"}>
...
</div>

结果是没有额外空格的className。

祝你有创意的一天!