React仅接受数字字符的Native TextInput

Ter*_*rry 68 react-native

我需要一个React Native TextInput组件,只允许输入数字字符(0 - 9).我可以设置keyboardTypenumeric几乎让我在那里除了周期输入().但是,这无法阻止将非数字字符粘贴到字段中.

到目前为止我所提出的是使用该OnChangeText事件来查看输入的文本.我从文本中删除任何非数字字符.然后将文本放在状态字段中.然后更新TextInput它的Value属性.下面的代码片段.

<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})
}
Run Code Online (Sandbox Code Playgroud)

这似乎工作,但它似乎是一个黑客.还有另一种方法吗?

Ven*_*omu 74

你可以这样做.它只接受数字值,并根据您的意愿限制为10个数字.

<TextInput 
   style={styles.textInput}
   keyboardType='numeric'
   onChangeText={(text)=> this.onChanged(text)}
   value={this.state.myNumber}
   maxLength={10}  //setting limit of input
/>
Run Code Online (Sandbox Code Playgroud)

您可以通过在页面中编写以下代码来查看输入的值:

{this.state.myNumber}
Run Code Online (Sandbox Code Playgroud)

在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 });
}
Run Code Online (Sandbox Code Playgroud)

我希望这对其他人有帮助.

  • 因为7恨9? (18认同)
  • 反正是为了防止闪烁? (4认同)

Jak*_*lor 69

使用RegExp替换任何非数字比使用带有白名单的for循环更快,就像其他答案一样.

将此用于onTextChange处理程序:

onChanged (text) {
    this.setState({
        mobile: text.replace(/[^0-9]/g, ''),
    });
}
Run Code Online (Sandbox Code Playgroud)

性能测试:https://jsperf.com/removing-non-digit-characters-from-a-string

  • 它工作正常,但是几乎没有闪烁,我们可以以任何方式克服吗 (6认同)
  • @CraZyDroiD只需调整正则表达式即可。如果只想匹配AZ,则需要`text.replace(/ [^ A-Za-z] / g,'')之类的东西。 (2认同)
  • 还将 `keyboardType='numeric'` 属性传递给 TextInput 字段。 (2认同)

Tjo*_*rie 15

这是正确的方法,直到专门开发这样的组件(或TextInput上的属性).

Web具有输入元素的"数字"类型,但这是基于Web的,而react-native不使用Web视图.

您可以考虑将该输入创建为它自己的反应组件(可能调用NumberInput):这将使您能够重用它,甚至可以开源它,因为您可以创建许多具有不同值过滤器/检查器的TextInput.

立即纠正的缺点是确保向用户提供正确的反馈,以防止混淆他的价值发生了什么


Vis*_*iya 14

第一个解决方案

您可以keyboardType = 'numeric'用于数字键盘。

  <View style={styles.container}>
        <Text style={styles.textStyle}>Enter Number</Text>
        <TextInput
          placeholder={'Enter number here'}
          style={styles.paragraph}
          keyboardType="numeric"
          onChangeText={value => this.onTextChanged(value)}
          value={this.state.number}
        />
      </View>
Run Code Online (Sandbox Code Playgroud)

在第一种情况下标点符号包括例如:- -

第二种解决方案

使用正则表达式去除标点符号。

 onTextChanged(value) {
    // code to remove non-numeric characters from text
    this.setState({ number: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
  }
Run Code Online (Sandbox Code Playgroud)

请检查小吃链接

https://snack.expo.io/@vishal7008/numeric-keyboard


Gan*_*hna 8

React Native TextInput为keyboardType道具提供以下可能的值:默认数字键盘,十进制键盘,数字电子邮件地址,电话键盘

因此对于您的情况,您可以使用keyboardType ='数字键盘'仅接受数字。不包括“。”

所以,

<TextInput 
  style={styles.textInput}
  keyboardType = 'number-pad'
  onChangeText = {(text)=> this.onChanged(text)}
  value = {this.state.myNumber}
/>
Run Code Online (Sandbox Code Playgroud)

是您必须使用的情况。

有关更多详细信息,请参阅TextInput的官方文档链接:https : //facebook.github.io/react-native/docs/textinput#keyboardtype

  • 问题是,如果用户使用键盘并连接物理键盘,软件约束键盘可能无法工作。 (2认同)

jas*_*ard 7

仅允许使用正则表达式的数字

<TextInput 
  keyboardType = 'numeric'
  onChangeText = {(e)=> this.onTextChanged(e)}
  value = {this.state.myNumber}
/> 

onTextChanged(e) {
  if (/^\d+$/.test(e.toString())) { 
    this.setState({ myNumber: e });
  }
}
Run Code Online (Sandbox Code Playgroud)

您可能要进行多个验证


<TextInput 
  keyboardType = 'numeric'
  onChangeText = {(e)=> this.validations(e)}
  value = {this.state.myNumber}
/> 

numbersOnly(e) {
    return /^\d+$/.test(e.toString()) ? true : false
}

notZero(e) {
    return /0/.test(parseInt(e)) ? false : true
}

validations(e) {
    return this.notZero(e) && this.numbersOnly(e)
        ? this.setState({ numColumns: parseInt(e) })
        : false
}

Run Code Online (Sandbox Code Playgroud)

  • @FrederikoCesar 看一下单一职责原则 (2认同)

小智 7

const [text, setText] = useState('');

const onChangeText = (text) => {
  if (+text) {
    setText(text);
  }
};

<TextInput
  keyboardType="numeric"
  value={text}
  onChangeText={onChangeText}
/>
Run Code Online (Sandbox Code Playgroud)

这应该可以避免物理键盘

  • 谢谢,我建议将 if(+text) 替换为 if (+text || text == "") 以允许空输入 (3认同)

Abd*_*han 6

验证输入的功能:

validateInputs(text, type) {
let numreg = /^[0-9]+$/;
  if (type == 'username') {
    if (numreg.test(text)) {
      //test ok
    } else {
      //test not ok
    } 
  }
}



<TextInput
   onChangeText={text => this.validateInputs(text, 'username')}
/>
Run Code Online (Sandbox Code Playgroud)

我希望这是有帮助的。


Ven*_*omu 5

这是我的另一个简单答案,使用正则表达式仅接受文本框中的数字。

onChanged(text){
    this.setState({ 
         myNumber: text.replace(/[^0-9]/g, '') 
    });
}
Run Code Online (Sandbox Code Playgroud)


Win*_*ing 5

谨此提醒那些遇到以下问题的人:“ onChangeText”无法按iOS预期的那样更改TextInput值:这实际上是ReactNative中的错误,并已在版本0.57.1​​中修复。请参阅:https//github.com/facebook/react-native/issues/18874

  • 抱歉,我没有足够的声誉来评论这个问题,所以我最终给出了一个答案,希望能引起人们对寻求可行解决方案的关注。 (2认同)

ANK*_*OJA 5

if (!/^[0-9]+$/.test('YourString')) {
  console.log('Enter Only Number');
} else {
    console.log('Success');
}
Run Code Online (Sandbox Code Playgroud)

  • 您好,请详细说明为什么这可以解决 OP 的问题。这将有助于 OP 和该网站的未来访问者。谢谢! (2认同)