chr*_*003 5 html javascript css reactjs
如何在点击时向现有的REACT元素添加CSS类?
我创建了一个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>
Run Code Online (Sandbox Code Playgroud)
您需要将所有状态参数添加到getInitialState,现在您唯一拥有的是color,所以this.state.color是那里唯一的东西
当您将状态设置为 className: Something 时,这是现在唯一的东西,甚至颜色都消失了......这就是为什么初始颜色是正常的淡灰色
你在 setState 中也有一个语法错误,它不是
this.setState({className = " green"});
Run Code Online (Sandbox Code Playgroud)
它应该是:
this.setState({className: " green"});
Run Code Online (Sandbox Code Playgroud)
最后,已弃用,您需要立即React.render使用ReactDOM.render
小提琴:https://jsfiddle.net/omarjmh/69z2wepo/36597/
| 归档时间: |
|
| 查看次数: |
21279 次 |
| 最近记录: |