夺命雷公狗-----React---21--小案例之心情留言板
这个功能如果是用传统型的jquery来写都要花费很多时间才可以完成的案例,
亲测jquery配合bootstrap来写和bootstrap配合react.js来写,不知不觉中有点震惊。。。
jquery版本代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="./css/bootstrap.css"> <script src="./js/jq18m.js"></script> <script src="./js/bootstrap.js"></script> </head> <body> <div class="container"> <br><br> <div class="well"> <textarea class="form-control" rows="10"></textarea> <br> <span>150</span> <button class="btn btn-default btn-primary pull-right" id="sub">OK</button> <button class="btn btn-default pull-right" id="pic">Add Pic</button> </div> </div> <script> //$('#sub').attr('disabled',true); $('#sub').prop('disabled',true); $('textarea').on('input',function(){ //alert('test'); var len = $(this).val().length; if(len>0){ $('#sub').prop('disabled',false); }else{ $('#sub').prop('disabled',true); } $('span').text(150 - len); }); $('#pic').on('click',function(){ $(this).toggleClass('uppic'); var len = $('textarea').val().length; if($(this).hasClass('uppic')){ $('span').text(150 - len - 24); //已经upload了图片 $(this).text('√ upload_OK'); }else{ //还没upload图片 $(this).text('Add Pic'); $('span').text(150 - len); } //判断下看下是否有内容 var lens = $('span').text(); if(lens< 150){ $('#sub').prop('disabled',false); }else{ $('#sub').prop('disabled',true); } }); </script> </body> </html>
react.js版本如下:
<!DOCTYPE> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="./css/bootstrap.css"> <script src="./js/jq11_1.js"></script> <script src="./js/bootstrap.js"></script> <script src="./js/react.js"></script> <script src="./js/react-dom.js"></script> <script src="./js/browser.min.js"></script> <style> *{ margin:0px; padding:0px;} </style> </head> <body> <div id="dome" class="container"></div> <div id="test"></div> <script type="text/babel"> var Fix = React.createClass({ getInitialState:function(){ return{ text:'',//表示大文本域的内容 uploaded:false //表示是否上传图片,默认否 } }, //计算剩余字数的方法 fontCount:function(){ //总数:150字 //要考虑text的长度和是否已经上传图片了 if(this.state.uploaded){ return 150 - 25 -this.state.text.length; }else{ return 150 - this.state.text.length; } }, handleChange:function(e){ this.setState({ text:e.target.value }); }, handleUpload:function(){ this.setState({ uploaded:!this.state.uploaded }); }, render:function(){ return( <div> <br /><br /> <div className="well"> <textarea className="form-control" rows="10" onChange={this.handleChange} > {this.props.text}</textarea> <br /> <span>{this.fontCount()}</span> <button className="btn btn-default btn-primary pull-right" disabled={this.state.text.length== 0 && !this.state.uploaded}>OK</button> <button className="btn btn-default pull-right" onClick={this.handleUpload}> {this.state.uploaded ? "√ upload_OK":"Add Pic"}</button> </div> </div> ); } }); ReactDOM.render( <Fix />, document.getElementById('dome') ); </script> </body> </html>
效果相同,但是代码量和逻辑处理react完胜。。。。。。。。。。。