我有一个TextInput,如何只启用小于9999.99的数字



我有一个文本输入,怎么可能只允许低于9999.99的数字?

<TextInput
autoFocus
style={styles.inputStyle}
placeholder="0.00"
keyboardType="numeric"
maxLength={9}
autoCapitalize="none"
placeholderTextColor={Colors.white}
underlineColorAndroid={Colors.transparent}
value={billAmount}
onChangeText={this.handleTextChange}
selection={{start: cursor, end: cursor}}
/>

以下是handleTextChange函数:

handleTextChange = (text) => {
const { cursor, billAmount } = this.state
let newText
newText = text.replace(/[^1-9]/g, '')
this.setState({
billAmount: newText
})
}

您的正则表达式还会删除任何点(.(。这将导致您失去任何浮动。如果要启用浮动,则需要将.添加到正则表达式中。

然后,您所需要做的就是将文本解析为浮点值,并检查它是否低于最大浮点值。

样本

handleTextChange = (text) => {
const newAmount = parseFloat(text.replace(/[^1-9.]/g, ''));
this.setState({
billAmount: newAmount > 10000 ? '9999.99' : newAmount + ''
});
}

最新更新