1.控件设置键盘为数字键盘(但是这控制不住,用户可以切换键盘)
<TextInput keyboardType='numeric'
placeholder={'请输入'}
underlineColorAndroid='transparent'
style={styles.labelNumText}
onChangeText={(text) => {
specialReportDataDetail.ticketPrice = formatPositiveNum(text, 2, 100000);
this.updateReportDetail(specialReportDataDetail);
}}
value={specialReportDataDetail.ticketPrice ? specialReportDataDetail.ticketPrice.toString() : ''}
/>
2.关键是输入内容校验
//格式化正数
// text:要格式化的文本
// decimalLength:小数位数
// max:转换为数字后最大值的限制
export function formatPositiveNum(text,decimalLength,max){
if(decimalLength==null||decimalLength<0){
ToastShort('小数位数不能小于0')
return;
}
if(decimalLength===0){
text = text.replace(/[^0-9]/g, '');
}else{
text = text.replace(/[^\.0-9]+/, '');
if(text!=null){
let dotArr = text.match(/\./g)
if(dotArr!=null&&dotArr.length>1){
text = text.replace(/.$/, '')
}
if(dotArr!=null&&dotArr.length===1){
let decimal = text.split('.')
if(decimal[1].length>decimalLength){
text = text.replace(/.$/, '')
}
}
}
}
if(max!==null&&text>max){
text = text.replace(/.$/, '')
}
return text;
}