React Native TextInput 只接受数字字符 [英] React Native TextInput that only accepts numeric characters

查看:35
本文介绍了React Native TextInput 只接受数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个只允许输入数字字符 (0 - 9) 的 React Native TextInput 组件.我可以将 keyboardType 设置为 numeric 几乎可以让我在那里输入除了句点 (.).然而,这并不能阻止将非数字字符粘贴到字段中.

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 numeric which almost gets me there for input except for the period (.). However this does nothing to stop pasting non-numeric characters into the field.

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

What I've come up with so far is to use the OnChangeText event to look at the text entered. I remove any non-numeric characters from the text. Then put the text in a state field. Then update the TextInput through it's Value property. Code snippet below.

<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})
}

这似乎有效,但它似乎是一个黑客.还有其他方法可以做到这一点吗?

This seems to work but it seems like a hack. Is there another way to do this?

推荐答案

在专门开发此类组件(或 TextInput 上的属性)之前,这是正确的做法.

That is the correct way to do it till such a component (or attribute on the TextInput) is specifically developed.

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

The web has the ‘number’ type for the input element, but that is web based and react-native does not use a web view.

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

You could consider to create that input as a react component on it’s own (maybe call NumberInput): that’ll enable you to reuse it or maybe even open source it since you can create many TextInputs that has different value filters/checkers.

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

The downside to immediate correction is to ensure correct feedback is given to the user as to prevent confusion as to what happened to his value

这篇关于React Native TextInput 只接受数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆