如何添加一个CSS类到现有的REACT元素点击?如何添加一个CSS类到点击元素 - 反应
我创建了一个的jsfiddle:this.setState({color:blue});
我想是这样this.setState({className: 'green'});
我在做什么错:https://jsfiddle.net/5r25psub/
在小提琴,如果我有语句的代码只适用?
代码:
<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>
您在'handleClick'里面写了'className =“green”'但它应该是'className:“green”' – jaybee