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

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

什么好主意吗?


当前回答

一个简单的语法是:

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

其他回答

一个简单的语法是:

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

不要想这么复杂的解决办法。

这是对你的问题最简单的解决办法。

<div className={`wrapper searchDiv ${this.state.something}`}>
   ...
</div>
className={css(styles.mainDiv, 'subContainer')}

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

同时添加import语句:

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

这里是动态className的最佳选项,只需做一些连接,就像我们在Javascript中做的那样。

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

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

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

\\ toggle condition

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