如何在单击时将CSS类添加到现有的REACT元素?
我创建了一个JSFiddle:https://jsfiddle.net/5r25psub/
在 fiddle 中,仅当我有以下语句时,代码才起作用:this.setState({color:blue});
我想要类似this.setState({className: 'green'});
的东西
我究竟做错了什么?
代码:
<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>
最佳答案
您可以使用在此处找到的模块classnames
:
https://www.npmjs.com/package/classnames
因此,您将执行以下操作:
getClassNames() {
return classNames({
'blue': this.state.clicked,
'green': !this.state.clicked
});
},
render () {
return <button className={this.getClassNames()} onClick={this.setState({clicked: !this.state.clicked})>
}
关于javascript - 如何在单击时将CSS类添加到元素-React,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36317933/