我试图阻止我的 TextInput 获得像 $,%,^,&,(,) etc
这样的值。基本上我的 TextInput 应该只允许字母。我的做法如下。但我仍然能够输入这些其他字符。我怎样才能防止来自 TextInput 的特殊字符
restrict(event) {
const regex = new RegExp("^[a-zA-Z]+$");
const key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
<TextInput
underlineColorAndroid='transparent'
allowFontScaling={false}
style={styles.questionText}
onKeyPress={e => this.restrict(e)}
value={firstNameState}
/>
原文由 CraZyDroiD 发布,翻译遵循 CC BY-SA 4.0 许可协议
android 上的 onKeyPress 事件效果不佳。
这就是为什么我选择使用一种方法来消除这些字符,然后将其保存在您想要的任何位置,就像它可能会改变您的字段状态一样。