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

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

什么好主意吗?


当前回答

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

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

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

祝你有创意的一天!

其他回答

一个简单的语法是:

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

你可以使用这个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})} />

如果你使用css模块,这对我来说是有用的。

const [condition, setCondition] = useState(false);

\\ toggle condition

return (
  <span className={`${styles.always} ${(condition ? styles.sometimes : '')`}>
  </span>
)
className={css(styles.mainDiv, 'subContainer')}

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

同时添加import语句:

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

[2022年4月21日更新:在反撇号之前和之后添加花括号以防止错误]

您可以简单地使用条件来应用所需的特定类

<div className={`wrapper searchDiv ${this.state.something ? "class that you want" : ""}`}>

如果你想使用makeStyle类,你可以像这样使用它

<div className={`wrapper searchDiv ${this.state.something ? classes.specifiedClass : ""}`}>