我需要有一个反应原生TextInput
组件,将只允许输入数字字符(0 - 9)。我可以将keyboardType
设置为numeric
,这样除了句点(.)之外,我几乎可以在那里输入。但是,这并不能阻止将非数字字符粘贴到字段中。
到目前为止,我想要的是使用OnChangeText
事件来查看输入的文本。我从文本中删除了所有非数字字符。然后将文本放在状态字段中。然后通过它的Value
属性更新TextInput
。下面的代码片段。
<TextInput
style={styles.textInput}
keyboardType = 'numeric'
onChangeText = {(text)=> this.onChanged(text)}
value = {this.state.myNumber}
/>
onTextChanged(text) {
// code to remove non-numeric characters from text
this.setState({myNumber: text})
}
这似乎是有效的,但它似乎是一个黑客。有没有其他方法可以做到这一点?
发布于 2015-10-06 03:55:14
在专门开发这样的组件(或TextInput上的属性)之前,这是正确的方法。
web有输入元素的‘number’类型,但这是基于web的,react-native不使用web视图。
您可以考虑将该输入创建为它自己的react组件(可以调用NumberInput):这将使您能够重用它,甚至可以将它开源,因为您可以创建许多具有不同值过滤器/检查器的TextInputs。
立即纠正的缺点是确保向用户提供正确的反馈,以防止混淆他的值发生了什么
发布于 2017-12-11 18:50:33
使用RegExp替换任何非数字比使用带有白名单的for循环更快,就像其他答案一样。
将此代码用于您的onTextChange处理程序:
onChanged (text) {
this.setState({
mobile: text.replace(/[^0-9]/g, ''),
});
}
性能测试地址:https://jsperf.com/removing-non-digit-characters-from-a-string
发布于 2016-11-25 18:59:13
你可以这样做。它将只接受数字值,并根据您的意愿限制为10个数字。
<TextInput
style={styles.textInput}
keyboardType='numeric'
onChangeText={(text)=> this.onChanged(text)}
value={this.state.myNumber}
maxLength={10} //setting limit of input
/>
您可以通过在页面中编写以下代码来查看输入的值:
{this.state.myNumber}
在onChanged()函数中,代码如下所示:
onChanged(text){
let newText = '';
let numbers = '0123456789';
for (var i=0; i < text.length; i++) {
if(numbers.indexOf(text[i]) > -1 ) {
newText = newText + text[i];
}
else {
// your call back function
alert("please enter numbers only");
}
}
this.setState({ myNumber: newText });
}
我希望这对其他人有帮助。
https://stackoverflow.com/questions/32946793
复制相似问题