1.限制輸入框只能填寫數(shù)字
大家都知道,在輸入框限制只能輸入數(shù)字用JS的來判斷要考慮的情況比較多,比如中文切換歪沃,復(fù)制粘貼限制米母,用reactJS來實現(xiàn)很簡單
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":"只能輸入數(shù)字!"});
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.限制輸入框的字數(shù)
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>
);
}
});