我有一个文本输入,怎么可能只允许低于 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
})
}
最佳答案
您的正则表达式还会删除所有点 (.
)。这将导致您失去任何 float 。如果您想启用 float ,您需要将 .
添加到您的正则表达式中。
然后您需要做的就是将文本解析为 float 并检查它是否低于最大 float 。
示例
handleTextChange = (text) => {
const newAmount = parseFloat(text.replace(/[^1-9.]/g, ''));
this.setState({
billAmount: newAmount > 10000 ? '9999.99' : newAmount + ''
});
}
关于javascript - 我有一个 TextInput,如何仅启用小于 9999.99 的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51323049/