CSS ReactJS 将动态类添加到手动类名

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

ReactJS add dynamic class to manual class names

cssreactjs

提问by Mankind1023

I need to add a dynamic class to a list of regular classes, but have no idea how (I'm using babel), something like this:

我需要将一个动态类添加到常规类列表中,但不知道如何(我正在使用 babel),如下所示:

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

Any ideas?

有任何想法吗?

回答by dannyjolie

You can either do this, normal JavaScript:

你可以这样做,普通的 JavaScript:

className={'wrapper searchDiv ' + this.state.something}

or the string template version, with backticks:

或字符串模板版本,带反引号:

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

Both types are of course just JavaScript, but the first pattern is the traditional kind.

这两种类型当然都只是 JavaScript,但第一种模式是传统类型。

Anyway, in JSX, anything enclosed in curly brackets is executed as JavaScript, so you can basically do whatever you want there. But combining JSX strings andcurly brackets is a no-go for attributes.

无论如何,在 JSX 中,用大括号括起来的任何东西都是作为 JavaScript 执行的,所以你基本上可以在那里做任何你想做的事。但是结合 JSX 字符串大括号对于属性来说是行不通的。

回答by Brad Colthurst

Depending on how many dynamic classes you need to add as your project grows it's probably worth checking out the classnamesutility by JedWatson on GitHub. It allows you to represent your conditional classes as an object and returns those that evaluate to true.

根据您在项目增长时需要添加的动态类的数量,可能值得在 GitHub 上查看JedWatson的类名实用程序。它允许您将您的条件类表示为一个对象,并返回那些评估为真的类。

So as an example from its React documentation:

因此,作为其 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>;

} 

Since React triggers a re-render when there is a state change, your dynamic class names are handled naturally and kept up to date with the state of your component.

由于 React 在状态更改时触发重新渲染,因此您的动态类名称会自然处理并与组件的状态保持同步。

回答by oligopol

A simple possible syntax will be:

一个简单的可能的语法是:

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

回答by Saad Mirza

Here is the Best Option for Dynamic className , just do some concatenation like we do in Javascript.

这是 Dynamic className 的最佳选项,只需像我们在 Javascript 中那样进行一些连接即可。

     className={
        "badge " +
        (this.state.value ? "badge-primary " : "badge-danger ") +
        " m-4"
      }

回答by Sergey Gubarev

If you need style names which should appear according to the state condition, I prefer to use this construction:

如果您需要根据状态条件出现的样式名称,我更喜欢使用这种结构:

<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>

回答by Hamza Khattabi

try this using hooks :

使用钩子试试这个:

        const [dynamicClasses, setDynamicClasses] = React.useState([
    "dynamicClass1", "dynamicClass2
]);

and add this in className attribute :

并将其添加到 className 属性中:

<div className=`wrapper searchDiv ${[...dynamicClasses]}`>
...
</div>

to add class :

添加类:

    const addClass = newClass => {
       setDynamicClasses([...dynamicClasses, newClass])
    }

to delete class :

删除类:

        const deleteClass= classToDelete => {

           setDynamicClasses(dynamicClasses.filter(class = > {
             class !== classToDelete
           }));

        }

回答by Tushar Sharma

You can use thisnpm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

你可以使用这个npm 包。它处理所有事情,并提供基于变量或函数的静态和动态类选项。

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />

回答by Harshvardhan Singh Baghel

getBadgeClasses() {
    let classes = "badge m-2 ";
    classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
    return classes;
}

<span className={this.getBadgeClasses()}>Total Count</span>

回答by Harjot Singh

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

This solution is tried and tested in React SPFx.

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

Also add import statement :

还要添加导入语句:

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