如何在点击时向元素添加CSS类 - React [英] How to add a CSS class to an element on click - React
问题描述
如何在点击时将CSS类添加到现有的REACT元素?
我创建了一个JSFiddle: https://jsfiddle.net / 5r25psub /
在小提琴中,代码仅适用于以下语句: this.setState({color:blue });
我想要类似于 代码: 您可以使用模块 https://www.npmjs.com/package/classnames 所以你可以这样做: How do you add a CSS class to an existing REACT element on click? I have a JSFiddle created: https://jsfiddle.net/5r25psub/ In the fiddle, the code only works if I have the statement: I want something like Code:
You can use the module https://www.npmjs.com/package/classnames So you would do something like:
这篇关于如何在点击时向元素添加CSS类 - React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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}>我的背景是:{this.state.color},点击我更改< / 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>
<! - 此元素的内容将被您的组件替换。 - >
< / div>
< / body>
< / html>
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})> ;
}
this.setState({color:blue});
this.setState({className: 'green'});
What am I doing wrong? <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
found here:getClassNames() {
return classNames({
'blue': this.state.clicked,
'green': !this.state.clicked
});
},
render () {
return <button className={this.getClassNames()} onClick={this.setState({clicked: !this.state.clicked})>
}