如下所示,设置
keyboardType='numeric'
,用户输入时就会弹出数字键盘,如果用户通过粘贴或者其他方式输入非数字时,通过正则表达式把非数字替换成空字符串
text.replace(/[^\d]+/, '')
,达到只能输入数字的目的。
代码如下:
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => {
const newText = text.replace(/[^\d]+/, '');
this.setState({inputValue: newText})
value={this.state.inputValue}
keyboardType='numeric'
————————2018-7-27更新分割线————————
评论区有程序猿反映在iOS上无效,我写了个实例测试。下面贴出完整代码及效果图,供大家学习。
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => {
const newText = text.replace(/[^\d]+/, '');
//可以打印看看是否过滤掉了非数字
console.log(newText)
this.setState({inputValue: newText})
value={this.state.inputValue}
//为了方便测试时输入字母,属性(keyboardType)不设置,实际使用时加上
// keyboardType='numeric'
</View>