Javascript 如何在单击时向元素添加 CSS 类 - React

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

How to add a CSS class to an element on click - React

javascripthtmlcssreactjs

提问by chrisrhyno2003

How do you add a CSS class to an existing REACT element on click?

如何在单击时将 CSS 类添加到现有的 REACT 元素?

I have a JSFiddle created: https://jsfiddle.net/5r25psub/

我创建了一个 JSFiddle:https://jsfiddle.net/5r25psub/

In the fiddle, the code only works if I have the statement: this.setState({color:blue});

在小提琴中,代码仅在我有以下语句时才有效: this.setState({color:blue});

I want something like this.setState({className: 'green'});What am I doing wrong?

我想要类似的东西this.setState({className: 'green'});我做错了什么?

Code:

代码:

    <html>
    <script>
        var Hello = React.createClass({
            getInitialState: function(){
                return {
                    color: 'blue'
                };
            },
            handleClick: function(){
                if (this.state.color === 'blue'){
                    this.setState({className = " green"});
                } else {
                    this.setState({color: 'blue'});
                }
            },
            render: function() {
                return <button className={this.state.className} onClick={this.handleClick}>My background is: {this.state.color}, Click me to change</button>;
            }
        });

        React.render(<Hello name="World" />, document.getElementById('container'));

    </script>
    <body>
    <script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<style>
.green {
    background-color: lightgreen;
}

.blue {
    background-color: lightblue;
}
</style>

    <div id="container">
        <!-- This element's contents will be replaced with your component. -->
    </div>
    </body>
    </html>

回答by sma

You can use the module classnamesfound here:

您可以使用classnames此处找到的模块:

https://www.npmjs.com/package/classnames

https://www.npmjs.com/package/classnames

So you would do something like:

所以你会做这样的事情:

getClassNames() {
    return classNames({
        'blue':  this.state.clicked,
        'green':  !this.state.clicked
    });
},
render () {
    return <button className={this.getClassNames()} onClick={this.setState({clicked: !this.state.clicked})>
}

回答by omarjmh

You need to add all state parameters to getInitialState, right now the only thing you have is color, so this.state.coloris the only thing in there

您需要添加所有的状态参数getInitialState,现在你拥有的唯一的事情是color,所以this.state.color是唯一的东西在那里

When you set your state to className: something, that is the only thing in there now, even color is gone...and that is why the initial color is the normal bland gray

当您将状态设置为 className: something 时,这是现在唯一的东西,甚至颜色都消失了……这就是为什么初始颜色是正常的淡灰色

you have a syntax error in setState as well, its not

你在 setState 中也有语法错误,它不是

this.setState({className = " green"});

It should be:

它应该是:

this.setState({className: " green"});

Finally, React.renderis deprecated, you need to use ReactDOM.rendernow

最后,React.render已被弃用,你需要使用ReactDOM.render现在

Fiddle: https://jsfiddle.net/omarjmh/69z2wepo/36597/

小提琴:https: //jsfiddle.net/omarjmh/69z2wepo/36597/

回答by Alexandr Lazarev

https://jsfiddle.net/ajvf50s6/3/

https://jsfiddle.net/ajvf50s6/3/

Most probably, you should better do a verification based on the className, not on the colorstate property:

最有可能的是,您最好根据className而非colorstate 属性进行验证:

handleClick: function(){
    if (this.state.className === 'blue'){
        this.setState({className: "green"});
    } else {
        this.setState({className: "blue"});
    }
}

Also, as @Omarjmh mentioned, you have a typo in your code. {className = " green"}is wrong assignment.

另外,正如@Omarjmh 所提到的,您的代码中有一个错字。{className = " green"}是错误的分配。

回答by Vinay J Rao

Rather than using two state variables, you can do like this.

您可以这样做,而不是使用两个状态变量。

Since the initial state of color is blue, you can change the handleClick function as :

由于颜色的初始状态是蓝色,您可以将 handleClick 函数更改为:

handleClick: function(){
 if (this.state.color === 'blue'){
  this.setState({color : "green"});
 } else {
   this.setState({color: 'blue'});
 }
}

And, for the className, consider a variable :

并且,对于 className,考虑一个变量:

let colorClass= this.state.color === "blue" ? "blue" : "green" 

Now, replace the className as below and you need to enclose that object where you call divclass.

现在,将 className 替换为如下所示,您需要将该对象包含在您调用div类的位置。

return <button className={colorClass} onClick={this.handleClick}>My background is: {this.state.color}, Click me to change</button>;

I hope it works fine.

我希望它工作正常。