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

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

什么好主意吗?


当前回答

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

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

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

祝你有创意的一天!

其他回答

className={css(styles.mainDiv, 'subContainer')}

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

同时添加import语句:

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

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

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

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

取决于你需要添加多少动态类,因为你的项目增长,它可能值得检查类名实用程序由JedWatson在GitHub。它允许您将条件类表示为对象,并返回那些求值为true的类。

举个React文档中的例子:

render () {

var btnClass = classNames({
  'btn': true,
  'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered
});

return <button className={btnClass}>I'm a button!</button>;

} 

由于React会在状态发生变化时触发重新渲染,因此动态类名会被自然地处理,并与组件的状态保持同步。

一个简单的语法是:

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

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

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

\\ toggle condition

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