简体   繁体   English

React-native货币输入

[英]React-native currency input

I'm trying to create a currency input, that starts as something like 我正在尝试创建一个货币输入,从类似的东西开始

" $00.00"

and then when you start typing, it types the cents first, then moves on to the dollars (ie, updates the right side numbers first), eg 然后当你开始输入时,它首先键入美分,然后转到美元(即首先更新右侧数字),例如

" $00.50"

So far I have it implemented, where the user types in one box, and the correctly formatted output displays in a second box. 到目前为止,我实现了它,用户在一个框中键入,并在第二个框中显示正确格式化的输出。

Code : 代码:

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>

    );

}

However, I want the currency formatting to apply to the same box the user is typing into. 但是,我希望货币格式应用于用户输入的同一个框。 I have tried something like this: 我试过这样的事情:

<TextInput 
        onChangeText={(amount) => this.setState({amount})}
        value = {this.formatValue(this.state.amount)}>
</TextInput>

but this simply sets the input to zero, and it cannot be changed. 但这只是将输入设置为零,并且无法更改。 I am clearly not understanding this correctly. 我显然不能正确理解这一点。

Does anyone have any insight on this? 有没有人对此有任何见解?

Maybe this package can help you out. 也许这个包可以帮到你。 It lets you store change value in state. 它允许您将更改值存储在状态中。

https://www.npmjs.com/package/react-currency-input https://www.npmjs.com/package/react-currency-input

Or since you only want to mask the input and not do any mutation/converting to the input you can of course do something like this; 或者既然你只想屏蔽输入而不做任何突变/转换到输入,你当然可以做这样的事情;

https://www.npmjs.com/package/react-input-mask https://www.npmjs.com/package/react-input-mask

I needed to do this exact thing in a recent project and I ended up releasing it as an npm package. 我需要在最近的项目中做到这一点,我最终将它作为npm包发布。

https://github.com/wwdrew/react-native-numeric-textinput https://github.com/wwdrew/react-native-numeric-textinput

It uses the Intl NumberFormat for formatting currencies and numbers, so should work for any currency you want to throw at it. 它使用Intl NumberFormat来格式化货币和数字,因此应该适用于您想要投入的任何货币。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM