抛砖引玉
先实现一个点击按钮切换背景的功能先。
默认背景色是红色,点击按钮在红绿色之间切换。
index.html
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>React</title> <link rel="stylesheet" href="css/style.css"/> </head> <body> <script src="js/lib/react.js"></script> <script src="js/lib/JSXTransformer.js"></script> <script src="js/app.js" type="text/jsx;harmony=true"></script> </body> </html>
style.css
.content { width: 100px; height: 100px; } .bg-red { background-color: red; } .bg-green { background-color: green; }
app.js
var DemoComponent = React.createClass({ getInitialState: function () { return {isBgRed: true}; },handleClick: function () { this.setState({isBgRed: !this.state.isBgRed}); },render: function () { var classString = 'content'; if (this.state.isBgRed) { classString = classString + ' bg-red'; } else { classString = classString + ' bg-green'; } return ( <div> <p className={classString}></p> <button onClick={this.handleClick}>toggle</button> </div> ) } }); React.render( <DemoComponent />,document.body );
效果
最后的页面效果就上面这样的,点击按钮实现了背景色的切换。回头来看看render方法里的这一坨内容
var classString = 'content'; if (this.state.isBgRed) { classString = classString + ' bg-red'; } else { classString = classString + ' bg-green'; }
这里根据状态切换不同的class,这种代码看起来太冗长,稍微改进下
var classString = 'content' + (this.state.isBgRed ? ' bg-red' : ' bg-green');
代码看起来要舒服些,但是还有一个问题,语义太差,阅读维护起来确实不大容易。为了解决这种类似组件className初始化或者动态切换的效果,React提供了工具ClassSet。
ClassSet
要想使用ClassSet,得先引入react-with-addons.js,可以去官网下载到。直接看代码
index.html
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>React</title> <link rel="stylesheet" href="css/style.css"/> </head> <body> <script src="js/lib/react.js"></script> <script src="js/lib/JSXTransformer.js"></script> <script src="js/lib/react-with-addons.js"></script> <script src="js/app.js" type="text/jsx;harmony=true"></script> </body> </html>
app.js
var cx = React.addons.classSet; var DemoComponent = React.createClass({ getInitialState: function () { return {isBgRed: true}; },render: function () { var classes = cx({ 'content': true,'bg-red': this.state.isBgRed,'bg-green': !this.state.isBgRed }); return ( <div> <p className={classes}>sdf</p> <button onClick={this.handleClick}>toggle</button> </div> ) } }); React.render( <DemoComponent />,document.body );