react-native TextInput只能输入纯数字

如下所示,设置keyboardType='numeric',用户输入时就会弹出数字键盘,如果用户通过粘贴或者其他方式输入非数字时,通过正则表达式把非数字替换成空字符串text.replace(/[^\d]+/, ''),达到只能输入数字的目的。

代码如下:

 {
    const newText = text.replace(/[^\d]+/, '');
    this.setState({inputValue: newText})
  }}
  value={this.state.inputValue}
  keyboardType='numeric'
/>

————————2018-7-27更新分割线————————

评论区有程序猿反映在iOS上无效,我写了个实例测试。下面贴出完整代码及效果图,供大家学习。

  • 效果图:


    react-native TextInput只能输入纯数字_第1张图片
    效果图.gif
  • 完整代码(新建一个文件,全部粘贴即可):
import React, { Component } from 'react';
import {
  View,
  TextInput,
} from 'react-native';

export default class Demo extends Component {

 constructor(props) {
    super(props);
    this.state = {
      inputValue: "",
    }
  }

  render() {
    return (
      
         {
            const newText = text.replace(/[^\d]+/, '');
            //可以打印看看是否过滤掉了非数字
            console.log(newText)
            this.setState({inputValue: newText})
          }}
          value={this.state.inputValue}
          //为了方便测试时输入字母,属性(keyboardType)不设置,实际使用时加上
          // keyboardType='numeric'
        />
      
    )
  }  
}
  • 设备信息和版本号
    测试手机:iPhone 6 (真机,而不是模拟器)
    react-native:0.51.0

注:如果没有达到效果,可以尝试换个环境,换真机测试,或者更换react-native版本。


如有疑问,看下图找答案!


你可能感兴趣的:(react-native TextInput只能输入纯数字)