我一直在思考如何最好地在 React JS 中有条件地应用 CSS 类。我已经看到了一些答案,但没有多少答案,或者它们没有我想要的那么详尽。
如何在 React JS 中有条件地应用 CSS 类
IT技术
javascript
css
reactjs
2021-04-28 16:55:45
4个回答
您可以简单地将类设置为状态,如下所示:
<div className={ this.state.exampleIsTruthy ? 'yourClass' : '' }>
text
</div>
或者如果你想根据这样的状态切换类:
<div className={ this.state.exampleTrueOrFalse ? 'shown' : 'hidden' }>
text
</div>
关于操作类名的 React 文档建议使用classnames
NPM 包。
该软件包的文档很棒。
以下代码段直接来自包README
:使用部分
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: false, bar: true }); // => 'bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true });
// => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, '');
// => 'bar 1'
许多答案都假设这是关于有条件地切换 CSS 类(如果足够,则为三元),但是当您需要选择性地包含类名时,这变得更加迟钝。带有空假表达式的多个三元 if 是冗长的。NPM 包可能有点多。对于某些人来说,一个函数也可能是矫枉过正。
这就是我所做的。
const classNames = [
"className1",
condition1 && "className2",
condition2 && "className3",
condition3 && "className4",
].filter(e => e).join(" ");
截至 2021 年 6 月编辑
我注意到这个答案仍然偶尔会看到赞成票。我想我会使用一个小而简洁的箭头函数提供一个稍微更新的例子:
const cls = (...classes) => classes.filter(Boolean).join(' ');
<div className={cls('mandatoryClass', condition && 'optionalClass')} />
如果您需要向现有类添加条件类,这个可能会给您一个想法
<span className={'fa ' + (this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down')}></span>
在这个例子中,我根据下拉菜单的状态显示了下拉菜单的箭头图标。我需要在fa
任何情况下保留类来设置跨度的字体系列,我只需要在fa-angle-up
和之间切换fa-angle-down
。
与模板文字相同的示例
<span className={`fa ${this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down'}`}></span>
其它你可能感兴趣的问题