我正在做一个关于 React Native 和 Typescript 的项目,我对它们很陌生,最近我遇到了一个我还无法解决的问题。我正在尝试在应用程序上进行登录,而 Typescript 不断在我所做的 useReducer 上给我错误。不幸的是,我是 Typescript 的新手,所以我只是在大多数类型上添加了任何错误,以修复以前的错误。这是代码登录时遇到预期错误,登录屏幕的输入:
import React, { useEffect, useReducer } from "react";
import { StyleSheet, Text, TextInput, View } from "react-native";
interface InputComponentProps {
INPUT_CHANGE: any
INPUT_BLUR: any
handleBlur: any
}
const INPUT_CHANGE: any = 'INPUT_CHANGE';
const INPUT_BLUR: any = 'INPUT_BLUR';
const inputReducer: any = (state: any, action: any) => {
switch(action.type) {
case INPUT_CHANGE:
return {
...state,
value: action.value,
isValid: action.isValid,
};
case INPUT_BLUR:
return {
...state,
touched: true,
};
default:
return state;
}
};
const InputComponent: React.FC = (props: any) => {
const [inputState, inputDispatch] = useReducer(inputReducer, {
value: '',
isValid: false,
touched: false,
});
const { onInputChange, id } = props;
useEffect((): (() => void) => {
return onInputChange(id, inputState.value, inputState.isValid);
}, [onInputChange, id, inputState])
const handleChangeText = (text: { trim: () => { (): any; new(): any; length: number; }; toLowerCase: () => string; length: number; }) => {
const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let isValid = true;
if (props.required && text.trim().length === 0) isValid = false;
if (props.email && !emailRegex.test(text.toLowerCase())) isValid = false;
if (props.minLength && text.length < props.minLength) isValid = false;
inputDispatch({
type: INPUT_CHANGE,
value: text,
isValid: isValid,
});
}
const handleBlur = () => inputDispatch({ type: INPUT_BLUR });
return (
<>
{props.label}
{!inputState.isValid && inputState.touched && (
{props.errorText}
)}
>
);
}
const styles = StyleSheet.create({
formControl: {
width: '100%',
},
label: {
fontFamily: 'OpenSansBold',
marginVertical: 8,
},
input: {
paddingHorizontal: 2,
paddingVertical: 5,
borderBottomColor: '#ccc',
borderBottomWidth: 1,
},
errorText: {
marginVertical: 5,
color: '#cc7755'
}
});
export default InputComponent;
这是错误截图:
p>
如果有人可以帮助我登录时遇到预期错误,我将不胜感激!