我正在尝试创建一个货币输入,开始时类似
" $00.00"
然后当您开始输入时,它会先输入美分,然后再输入美元(即首先更新右侧的数字),例如
" $00.50"
到目前为止,我已经实现了它,用户在一个框中键入内容,然后在第二个框中显示格式正确的输出。
代码:
constructor(props) {
super(props);
this.state = {
amount: '',
};
}
formatValue(value) {
return accounting.formatMoney(parseFloat(value) / 100, "$ ");
}
render() {
return (
<ScrollView>
<Text style={styles.text}> Enter the Amount to be payed</Text>
<TextInput
onChangeText={(amount) => this.setState({amount})}>
</TextInput>
<TextInput
onChangeText = {amount => this.setState({amount})}
value={this.formatValue(this.state.amount)}>
</TextInput>
</ScrollView>
);
}
但是,我希望货币格式应用于用户正在输入的同一个框。我试过这样的事情:
<TextInput
onChangeText={(amount) => this.setState({amount})}
value = {this.formatValue(this.state.amount)}>
</TextInput>
但这只是将输入设置为零,并且无法更改。我显然没有正确理解这一点。
有没有人对此有任何见解?
最佳答案
我需要在最近的一个项目中做这件事,我最终将它作为一个 npm 包发布。
https://github.com/wwdrew/react-native-numeric-textinput
它使用 Intl NumberFormat 来格式化货币和数字,因此应该适用于您想要投入其中的任何货币。
关于javascript - React-原生货币输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436951/