如何在React JS中有条件地应用CSS类

Mr.*_*ict 13 javascript css reactjs

我一直在思考如何最好地在React JS中有条件地应用CSS类.我已经看到一些答案,但是那里没有很多,或者它们并不像我想的那么精致.

Ros*_*len 18

关于操作类名的React文档建议使用classnamesNPM包.包的文档很棒.以下代码片段直接来自包的自述文件:

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'
Run Code Online (Sandbox Code Playgroud)


Ada*_*lov 15

没有classNames库,您可以简单地将类调整为状态,如下所示:

<div className={ this.state.end ? 'hidden' : 'shown' }>
    text
</div>
Run Code Online (Sandbox Code Playgroud)


Aud*_*sen 11

许多答案都假设这是关于有条件地切换 CSS 类(如果足够,则为三元),但是当您需要选择性地包含类名时,这变得更加迟钝。带有空假表达式的多个三元 if 是冗长的。NPM 包可能有点多。对于某些人来说,一个函数也可能是矫枉过正。

这就是我所做的。

const classNames = [
  "className1",
  condition1 && "className2",
  condition2 && "className3",
  condition3 && "className4",
].filter(e => e).join(" ");
Run Code Online (Sandbox Code Playgroud)

截至 2021 年 6 月编辑

我注意到这个答案仍然偶尔会看到赞成票。我想我会使用一个小而简洁的箭头函数提供一个稍微更新的例子:

const cls = (...classes) => classes.filter(Boolean).join(' ');

<div className={cls('mandatoryClass', condition && 'optionalClass')} />
Run Code Online (Sandbox Code Playgroud)


Ork*_*zel 5

如果您需要在现有类中添加条件类,这个可能会给您一个想法

<span className={'fa ' + (this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down')}></span>
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我根据下拉菜单的状态显示了下拉菜单的箭头图标。我需要在fa任何情况下保留类来设置跨度的字体系列,我只需要在fa-angle-up和之间切换fa-angle-down

与模板文字相同的示例

<span className={`fa ${this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down'}`}></span>
Run Code Online (Sandbox Code Playgroud)


Mr.*_*ict -2

好吧,所以我一直在尝试,结果证明是有办法的,而且并不像我想象的那么难。\n这可能会对那些刚刚开始使用 React JS 的人有所帮助。

\n\n

因此有两种方法可以实现这一点,并且添加内联样式有两个原因:

\n\n

(1) 在样式属性内添加类名作为对象,以便可以在常规 CSS 样式表内、直接在 JSX 文件内设置样式或用于条件 CSS

\n\n

实施例1

\n\n
const classNameAsAPlainObject = {\n        color: \'#333333\',\n        backgroundColor: \'#999999\'\n}\n\n<a href="#" className="an-existing-class" style={classNameAsAPlainObject} >\nButton\n</a>\n
Run Code Online (Sandbox Code Playgroud)\n\n

实施例2

\n\n
const conditionIsSomething = {\n    color: \'red\'\n}\n<a href="#" className="an-existing-class" style={conditionIsSomething ? \'classNameBasedOnCondition\' : \' \' }>\nButton\n</a>\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

在第二个示例中,可以根据所需结果声明两个不同的类,或者如果条件为真则可以声明一个类,如果条件为假则可以声明一个类。

\n
\n\n

(2) 将其添加到需要条件的常规 className 属性中,但一定要适应现有的类名称,并注意此方法需要在常规 CSS 文件中设置样式。如果不需要任何条件,则按正常方式将类添加到 className 属性。

\n\n

实施例3

\n\n
<a href="#" className={"an-existing-class " + (conditionIsSomething ? \'thisClass\' : \'thatClass\')}>\nButton\n</a>\n
Run Code Online (Sandbox Code Playgroud)\n\n

实施例4

\n\n
<a href="#" className={"an-existing-class " + (conditionIsSomething ? \'aClassIsAdded\' : \' \')}>\nButton\n</a>\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

同样,如果条件需要,可以声明一个类,也可以声明一个类,如示例 4 所示。无论哪种情况,请务必在“an-existing-class”之后和结束引号之前留一个空格,以便有\xe2\x80\x99s 条件类的空格\n。

\n
\n\n

因此,我猜想作为一般经验法则,您要添加一个类并将样式设置为对象(与示例 1 和 2 一样),您可以在 JSX 文件中设置它的样式,但是如果将类名添加到“className " 属性,您将在常规 CSS 文件中设置它的样式。我实际上还没有尝试过这个,所以我会尝试一下。如果有人发现其他情况,请赐教。

\n