如何在单击时将 CSS 类添加到现有的 REACT 元素?
我创建了一个 JSFiddle:https ://jsfiddle.net/5r25psub/
在小提琴中,代码仅在我有以下语句时才有效: 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>