1.限制输入框只能填写数字
大家都知道,在输入框限制只能输入数字用JS的来判断要考虑的情况比较多,比如中文切换,复制粘贴限制,用reactJS来实现很简单
var _val = ""; /*保存上次的值*/ var R_header = React.createClass({ getInitialState:function(){ return {info:""}; }, changeVal:function(e){ var val = e.target.value; if(isNaN(val)){ val = _val; this.setState({"info":"只能输入数字!"}); setTimeout(function(){ this.setState({"info":""}); }.bind(this),1000); }else{ _val = val; } this.setState({"val":val}); }, render:function(){ return ( <div> <input type="text" defaultValue="" name="title" value={this.state.val} onChange={this.changeVal} /> <label for="title">{this.state.info}</label> </div> ); } });
2.限制输入框的字数
changeVal:function(e){ var val = e.target.value; var length = val.length; this.setState({"i_val":val.substring(0,10)}); if(length > 10){ this.setState({"info":"不能输入超过10个字!"}); setTimeout(function(){ this.setState({"info":""}); }.bind(this),1000); }else{ this.setState({"info":""}); } }, render:function(){ return ( <div> <input type="text" defaultValue="" name="title" value={this.state.i_val} onChange={this.changeVal} /> <label for="title">{this.state.info}</label> </div> ); }
3.即时显示还可以输入多少个字
var R_header = React.createClass({ getInitialState:function(){ return {info:10}; }, changeVal:function(e){ var val = e.target.value; var length = val.length; this.setState({"i_val":val.substring(0,10)}); length < 11?this.setState({"info":(10-length)}):""; }, render:function(){ return ( <div> <input type="text" defaultValue="" name="title" value={this.state.i_val} onChange={this.changeVal} /> <label for="title">您还可以输入{this.state.info}个字</label> </div> ); } });