用户输入验证无法正常工作

Shariq·艾哈迈德·汗:

我试图让我的应用程序ReactNative中的一个组件,让用户可以只给数字输入,但我的JavaScript reg表达式不能正常工作。我用母语作出反应钩来管理国家。我想验证用户输入的唯一号码,但输入文本字段也与空字符串代替数字。该部件的代码是follwoing;

import React, { useState } from 'react';
import { StyleSheet, Text, View, TextInput, Button, TouchableOpacity } from 'react-native';
import Card from '../components/Card';
import Colors from '../constants/Colors';
import Input from '../components/Input';


const StartGameScreen = props => {

  const [enteredValue, setEnteredValue] = useState ('');

  const numberInputHandler = inputText => {
    setEnteredValue (inputText.replace(/[^0-9]/g, ''));
  };

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Start a New Game</Text>
      <Card style={styles.inputContainer}>
        <Text>Select a Number</Text>
        <Input style={styles.inputText} 
        blurOnSubmit 
        auotCaptalize={'none'} 
        autoCorrect={false} 
        maxLength={2} 
        keyboardType={'number-pad'}
        onChnageText={numberInputHandler}
        value={enteredValue}
        />
        <View style={styles.buttonContainer}>
          <TouchableOpacity activeOpacity={0.4} style={{backgroundColor: Colors.accent, ...styles.button}}>
            <Text style={styles.buttonText}>Reset</Text>
          </TouchableOpacity>
          <TouchableOpacity activeOpacity={0.4} style={{backgroundColor: Colors.primary, ...styles.button}}>
            <Text style={styles.buttonText}>Confirm</Text>
          </TouchableOpacity>
        </View>
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    padding: 10,
    alignItems: 'center'
  },
  button: {
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    height: 35,
    width: 80
  },
  buttonText: {
    color: 'white'
  },
  title: {
    fontSize: 20,
    marginVertical: 10
  },
  inputContainer: {
    padding: 10,
    width: 300,
    height: 120,
    maxWidth: '80%'
  },
  inputText: {
    width: 35,
    textAlign: "center",
  },
  buttonContainer: {
    height: 30,
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    alignItems: "center"
  }
});

export default StartGameScreen;

为输入组件的代码是下面;

import React from 'react';
import { TextInput, StyleSheet} from 'react-native';

const Input = props => {
    return (
        <TextInput {...props} style={{...styles.input, ...props.style}}/>
    );
}

const styles = StyleSheet.create({
    input: {
        height: 30,
        borderBottomWidth: 1,
        borderBottomColor: 'grey',
        marginVertical: 10
    }
});

export default Input;
巴里迈克尔多伊尔:

你拼错道具在你实现Input你的StartGameScreen组件,它负责处理变化。

onChnageText 应该 onChangeText

原因您的非数字“改为”以及实际上是因为更改处理没有映射到onChangeText归因于错字。

额外的注意事项:

你还在你做另一个错字Input实现。

auotCaptalize 应该 autoCapitalize

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章