Javascript 如何将多个类添加到 ReactJS 组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34521797/
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 16:29:30  来源:igfitidea点击:

How to add multiple classes to a ReactJS Component

javascriptcssreactjsecmascript-6

提问by Hector

I am new to ReactJS and JSX and I am having a little problem with the code below.

我是 ReactJS 和 JSX 的新手,我对下面的代码有一点问题。

I am trying to add multiple classes to the classNameattribute on each li:

我正在尝试向className每个属性添加多个类li

<li key={index} className={activeClass, data.class, "main-class"}></li>

My React component is:

我的反应组件是:

var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help &amp; Support &nbsp; <span class='font-awesome icon-support'></span>(888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (
      <div className="acc-header-wrapper clearfix">
        <ul className="acc-btns-container">
          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (
              <li
                key={index}
                className={activeClass}
                onClick={self.clicked.bind(self, index)}
              >
                <a href="#" className={data.icon}>
                  {data.name}
                </a>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));

采纳答案by Hyman

I use classnameswhen there is a fair amount of logic required for deciding the classes to (not) use. An overly simple example:

当决定要(不)使用的类需要大量逻辑时,我会使用类名。一个过于简单的例子

...
    var liClasses = classNames({
      'main-class': true,
      'activeClass': self.state.focused === index
    });

    return (<li className={liClasses}>{data.name}</li>);
...

That said, if you don't want to include a dependency then there are better answers below.

也就是说,如果您不想包含依赖项,那么下面有更好的答案。

回答by Damjan Pavlica

I use ES6template literals. For example:

我使用ES6模板文字。例如:

const error = this.state.valid ? '' : 'error'
const classes = `form-control round-lg ${error}`

And then just render it:

然后渲染它:

<input className={classes} />

One-liner version:

单线版:

<input className={`form-control round-lg ${this.state.valid ? '' : 'error'}`} />

回答by 0xcaff

Just use JavaScript.

只需使用 JavaScript。

<li className={[activeClass, data.klass, "main-class"].join(' ')} />

If you want to add classes based keys and values in an object you can use the following:

如果要在对象中添加基于类的键和值,可以使用以下命令:

function classNames(classes) {
  return Object.entries(classes)
    .filter(([key, value]) => value)
    .map(([key, value]) => key)
    .join(' ');
}

const classes = {
  'maybeClass': true,
  'otherClass': true,
  'probablyNotClass': false,
};

const myClassNames = classNames(classes);
// Output: "maybeClass otherClass"

<li className={myClassNames} />

Or even simpler:

或者更简单:

const isEnabled = true;
const isChecked = false;

<li className={[isEnabled && 'enabled', isChecked && 'checked']
  .filter(e => !!e)
  .join(' ')
} />
// Output:
// <li className={'enabled'} />

回答by Jamie Hutber

Concat

康卡特

No need to be fancy I am using CSS modules and it's easy

无需花哨,我正在使用 CSS 模块,这很容易

import style from '/css/style.css';

<div className={style.style1+ ' ' + style.style2} />

This will result in:

这将导致:

<div class="src-client-css-pages-style1-selectionItem src-client-css-pages-style2">

In other words, both styles

换句话说,两种风格

Conditionals

条件句

It would be easy to use the same idea with if's

将相同的想法与 if 一起使用会很容易

const class1 = doIHaveSomething ? style.style1 : 'backupClass';

<div className={class1 + ' ' + style.style2} />

回答by Cody Moniz

This can be achieved with ES6 template literals:

这可以通过 ES6 模板文字来实现:

<input className={`class1 ${class2}`}>

回答by nightlyop

You can create an element with multiple class names like this:

您可以创建具有多个类名的元素,如下所示:

<li className="class1 class2 class3">foo</li>

Naturally, you can use a string containing the class names and manipulate this string to update the class names of the element.

当然,您可以使用包含类名的字符串并操作该字符串来更新元素的类名。

var myClassNammes = 'class1 class2 class3';
...
<li className={myClassNames}>foo</li>

回答by Hristo Eftimov

This is how you can do that with ES6:

这就是你可以用 ES6 做到这一点的方法:

className = {`
      text-right
      ${itemId === activeItemId ? 'active' : ''}
      ${anotherProperty === true ? 'class1' : 'class2'}
`}

You can list multiple classes and conditions and also you can include static classes. It is not necessary to add an additional library.

您可以列出多个类和条件,也可以包含静态类。没有必要添加额外的库。

Good luck ;)

祝你好运 ;)

回答by Huw Davies

Vanilla JS

香草JS

No need for external libraries - just use ES6 template strings:

不需要外部库 - 只需使用 ES6模板字符串

<i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>

回答by xsong

Maybe classnamescan help you.

也许类名可以帮助你。

var classNames = require('classnames');
classNames('foo', {'xx-test': true, bar: false}, {'ox-test': false}); // => 'foo xx-test'

回答by Pasham Akhil Kumar Reddy

I don't think we need to use an external package for just adding multiple classes.

我认为我们不需要使用外部包来添加多个类。

I personally use

我个人使用

<li className={`li active`}>Stacy</li>

or

或者

<li className={`li ${this.state.isActive ? 'active' : ''}`}>Stacy<li>

the second one in case you need to add or remove classes conditionally.

第二个,以防您需要有条件地添加或删除类。