我正在尝试在ReactNative应用程序中创建一个组件,在该组件中,用户只能输入数字作为输入,但是我的JavaScript reg表达式无法正常工作。我使用React Native钩子来管理状态。我正在尝试仅验证用户输入的数字,但输入文本字段还将数字替换为空字符串。该组件的代码如下;
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;
答案 0 :(得分:0)
在负责处理更改的Input
组件上执行StartGameScreen
的道具时,拼写错误。
onChnageText
应该是onChangeText
您的非数字也被“替换”的原因实际上是因为该错字未将更改处理程序映射到onChangeText
。
附加说明:
您还在Input
实现中输入了另一个错字。
auotCaptalize
应该是autoCapitalize
答案 1 :(得分:0)
有两个拼写错误:
Type mismatch, expected: NotInferedM[Future[NotInferedA]], actual: [Future[Either[Error, Unit]]]
应该是auotCaptalize={'none'}
,而autoCapitalize={'none'}
应该是onChnageText={numberInputHandler}