如何添加一個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