您的位置:首页 > Web前端 > React

react native输入框 输入金额等数据后如何格式化显示

2016-11-25 15:35 1391 查看
import React ,{ Component } from 'react';
import {View} from 'react-native';
import {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
CellText,
Input,
Label,
} from 'rn-weui/src';
export class InputBox extends Component{
constructor(props) {
super(props);
this.state = {
money:'',
endEdit:true
};
this.fmoney = this.fmoney.bind(this);
}
/**
* 格式化money
* s为要格式化的money
* n为小数位数
*/
fmoney(s, n){
if(s==='')
return;
n = n > 0 && n <= 20 ? n : 2;
s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
var l = s.split(".")[0].split("").reverse(),
r = s.split(".")[1];
var t = "";
for(let i = 0; i < l.length; i ++ ) {
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
}
return t.split("").reverse().join("") + "." + r;
}

render(){
return (
<Cells>
<Cell>
<CellHeader><Label>单价</Label></CellHeader>
<CellBody>
<View>
<Input style={{height:40}}
underlineColorAndroid="transparent"
placeholder="请输入金额"
keyboardType='numeric'
value={this.state.endEdit?this.fmoney(this.state.money,2):this.state.money+''}
onChangeText={(text)=>{
this.setState({money:text});
}}
onFocus={()=>{
// this.setState({endEdit:false});
this.setState({endEdit:false,money:''});
}}
onEndEditing={(event) => {
this.setState({endEdit:true});
}}
></Input>
</View>
</CellBody>
<CellFooter>元</CellFooter>
</Cell>

<Cell>
<CellHeader><Label>单价</Label></CellHeader>
<CellBody>
<View>
<Input style={{height:40}}
underlineColorAndroid="transparent"
placeholder="请输入物品单价"
keyboardType='numeric'
></Input>
</View>
</CellBody>
<CellFooter>元</CellFooter>
</Cell>
</Cells>
);
}
}


首先,state声明一个输入框是否正在输入的状态endEdit和一个用来表示输入框中显示的值money; 然后,在onblue获得焦点的实践中,将是否正在输入的状态改为false,输入框中的显示money;输入完成,将endEdit改为出,输入框中的值改为格式化后的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐