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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39281032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:25:08  来源:igfitidea点击:

How to conditionally apply CSS classes in React JS

javascriptcssreactjs

提问by Mr. Benedict

I've been musing on how best to conditionally apply a CSS class in React JS. I've seen some answers banding around but there aren't many out there or they're just not as elaborative as I'd like.

我一直在思考如何最好地在 React JS 中有条件地应用 CSS 类。我已经看到了一些答案,但没有多少答案,或者它们没有我想要的那么详尽。

回答by Ross Allen

The React documentation on manipulating class namessuggests the classnamesNPM package.

关于操作类名的 React 文档建议使用classnamesNPM 包。

The docs for the package are great.

该软件包的文档很棒。

The following snippet is straight from the package README: Usagesection

以下代码段直接来自包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'

回答by Adam Orlov

You can simply condition class to state, like this:

您可以简单地将类设置为状态,如下所示:

<div className={ this.state.exampleIsTruthy ? 'yourClass' : '' }>
  text
</div>

or if you want to switch classes based on a state like this:

或者如果你想根据这样的状态切换类:

<div className={ this.state.exampleTrueOrFalse ? 'shown' : 'hidden' }>
  text
</div>

回答by Alok Ranjan

The solution which is stated below by other author in above comment works for me

其他作者在上述评论中陈述的解决方案对我有用

<div className={ this.state.end ? 'hidden' : 'shown' }>text</div>

Just a add on if you want to add more classes then add class separated by space.

如果您想添加更多类然后添加以空格分隔的类,只需添加即可。

回答by Denis Ivanov

Use Classnames library https://github.com/JedWatson/classnames

使用类名库https://github.com/JedWatson/classnames

The classNames function takes any number of arguments which can be a string or object. If the value of the key is falsy, it won't be included in the output.

classNames 函数接受任意数量的参数,这些参数可以是字符串或对象。如果键的值是假的,它将不会包含在输出中。

var classNames = require('classnames');

var Button = React.createClass({
  // ...
  render () {
    var btnClass = classNames({
      'btn': true,
      'btn-pressed': false,
      'btn-over': true
    });
    // output: btnClass = "btn btn-over"
    return <button className={btnClass}>{this.props.label}</button>;
  }
});

Take a look at the doc and let me know if you have any questions!

看看文档,如果您有任何问题,请告诉我!

Cheers

干杯

回答by bmceldowney

For the record I think the classnameslibrary answers are the most correct, but if you didn't want to pull in another dependency, you could roll your own simple implementation that works kind of like jQuery:

作为记录,我认为classnames库的答案是最正确的,但是如果您不想引入另一个依赖项,则可以推出自己的简单实现,其工作方式类似于 jQuery:

function getClassBuilder () {
    return {
        array: [],
        add: function (className) {
            if (this.array.indexOf(className) < 0) {
                this.array.push(className);
            }
        },
        remove: function (className) {
            var index = this.array.indexOf(className);
            if (index > -1) {
                this.array.splice(index, 1);
            }
        },
        toString: function () {
            return this.array.join(' ');
        }
    }
}

then, when you need to use it:

然后,当您需要使用它时:

var builder = getClassBuilder();
builder.add('class1');
builder.add('class2');
if (condition) { builder.remove('class1') };

<a href="#" className={builder.toString()}>Button</a>

回答by Orkun Tuzel

If you need to add a conditional class to an existing class, this one may give you an idea

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

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

in this example, I am showing an arrow icon for a dropdown depending on the state of the dropdown. I need to keep the class fafor any case to set the font-family of the span, and I only need to switch between fa-angle-upand fa-angle-down.

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

Same example with template literals

与模板文字相同的示例

<span className={`fa ${this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down'}`}></span>

回答by Audun Olsen

Many answers assume this is about conditionally toggling CSS classes (ternary ifis adequate), but this become far more obtuse when you need to optionally include classnames. Multiple ternary ifs with empty false expressions is verbose. An NPM package may be a tad much. A function too may be overkill for some.

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

Here's what I do.

这就是我所做的。

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

回答by Yilmaz

I will illustrate on bootstrap classes, will change the color of the text conditionally: If count=0 text will be red, otherwise will be blue

我将在 bootstrap 类上进行说明,将有条件地更改文本的颜色:如果 count=0 文本将是红色,否则将是蓝色

class Counter extends Component {
  state = { count: 6 };

  render() {
let classes="text-center" //class is reserved word in react.js
classes+= (this.state.count===0) ? "text-danger" : "text-primary"
    return (
      <div>
        <h2 className={classes}>Hello World</h2>
      </div>
    );
  }
  formatCount() {
    const { count } = this.state;
    return count === 0 ? "zero" : count;
  }
}

回答by Mr. Benedict

Ok, so I've been experimenting and it turns out there are ways and it's not as hard as I thought. This might help those just starting out in React JS.

好的,所以我一直在试验,结果证明有很多方法,而且并不像我想象的那么难。这可能会帮助那些刚开始使用 React JS 的人。

So there are two ways of doing so and two reasons for adding in-line styles:

所以有两种方法和两个添加内嵌样式的原因:

(1) Add class name inside a style attribute as an object so it can be styled inside a regular CSS stylesheet, directly inside a JSX file or used for conditional CSS

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

EXAMPLE 1

例 1

const classNameAsAPlainObject = {
        color: '#333333',
        backgroundColor: '#999999'
}

<a href="#" className="an-existing-class" style={classNameAsAPlainObject} >
Button
</a>

EXAMPLE 2

例2

const conditionIsSomething = {
    color: 'red'
}
<a href="#" className="an-existing-class" style={conditionIsSomething ? 'classNameBasedOnCondition' : ' ' }>
Button
</a>

In the second example, two different classes can be declared depending on desired result or one class can be declared if condition is true or none if condition is false.

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

(2) Add it to the regular className attribute where a condition is required but be sure to accommodate for existing class names and be aware that this method requires styling in a regular CSS file. If no condition is required, then add the class as per normal to a className attribute.

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

EXAMPLE 3

例3

<a href="#" className={"an-existing-class " + (conditionIsSomething ? 'thisClass' : 'thatClass')}>
Button
</a>

EXAMPLE 4

例4

<a href="#" className={"an-existing-class " + (conditionIsSomething ? 'aClassIsAdded' : ' ')}>
Button
</a>

Again, if the condition requires it, one class can be declared or none as seen in example 4. Be sure to leave a space in either case after the "an-existing-class" and before the closing quote so there's a space for the conditional class.

同样,如果条件需要,则可以声明一个类或不声明一个类,如示例 4 所示。确保在任何一种情况下都在“an-existing-class”之后和结束引号之前留一个空格,以便有一个空格用于条件类。

So I guess as a general rule of thumb, you're adding a class and styling as an object (as with Example 1 and 2), you can style it within the JSX file, but if adding a class name to the "className" attribute, you will be styling it inside a regular CSS file. I haven't experimented with this actually so I will give that a try. If anyone finds otherwise, please enlighten me.

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