React Native TextInput that only accepts numeric characters

前端 未结 19 1093
轮回少年
轮回少年 2020-12-02 10:38

I need to have a React Native TextInput component that will only allow numeric characters (0 - 9) to be entered. I can set the keyboardType to

19条回答
  •  -上瘾入骨i
    2020-12-02 11:35

    Using a RegExp to replace any non digit. Take care the next code will give you the first digit he found, so if user paste a paragraph with more than one number (xx.xx) the code will give you the first number. This will help if you want something like price, not a mobile phone.

    Use this for your onTextChange handler:

    onChanged (text) {
        this.setState({
            number: text.replace(/[^(((\d)+(\.)\d)|((\d)+))]/g,'_').split("_"))[0],
        });
    }
    

提交回复
热议问题