问题描述
我正在做一个使用 Native-Base 样式库的 Expo/React-Native 项目。为了验证表单,我正在使用 Formik + 是的。
所以我有这个登录屏幕,并且“onSubmit”方法只在验证工作时被调用,但是当验证失败时它不会显示错误,即使我选择用
这是我登录屏幕的相关部分
export default function LoginScreen(props) {
const { handleChange,handleSubmit,handleBlur,values,errors } = useFormik({
initialValues: { username: "",password: "" },validationSchema: LoginSchema,onSubmit: (values) => {
console.log(values);
},});
return (
<SafeAreaView>
<Center width="90%">
<FormControl marginTop={10} marginBottom={5}>
<FormControl.Label>Email ou nome de usuário</FormControl.Label>
<Input
type="text"
onChangeText={handleChange("username")}
onBlur={handleBlur("username")}
value={values.username}
/>
<FormControl.ErrorMessage>{errors.username}</FormControl.ErrorMessage>
</FormControl>
<FormControl>
<FormControl.Label>Senha</FormControl.Label>
<Input
type="password"
onBlur={handleBlur("password")}
onChangeText={handleChange("password")}
secureTextEntry={true}
value={values.password}
/>
<FormControl.ErrorMessage>{errors.password}</FormControl.ErrorMessage>
</FormControl>
<Button marginTop={5} onPress={handleSubmit}>
Login
</Button>
</Center>
</SafeAreaView>
);
}
这里是 Yup 验证架构
export const LoginSchema = Yup.object().shape({
username: Yup.string().required("Este campo é obrigatório"),password: Yup.string()
.max(20,"Senha muito longa")
.required("Este campo é obrigatório"),});
解决方法
也许错误出在您的 <FormControl.ErrorMessage>
组件中。我用 React Native 组件做了一个测试,它的代码运行良好:
import React from 'react';
import {View,Text,TextInput,Button} from 'react-native';
import {useFormik} from 'formik';
import * as Yup from 'yup';
const App = () => {
const {handleChange,handleSubmit,values,errors} = useFormik({
initialValues: {username: '',password: ''},validationSchema: Yup.object().shape({
username: Yup.string().required('Este campo é obrigatório'),password: Yup.string()
.max(20,'Senha muito longa')
.required('Este campo é obrigatório'),}),onSubmit: values => {
console.log(values);
},});
return (
<View>
<Text>Email</Text>
<TextInput
value={values.username}
onChangeText={handleChange('username')}
/>
<Text>{errors.username}</Text>
<Text>Senha</Text>
<TextInput
value={values.password}
onChangeText={handleChange('password')}
/>
<Text>{errors.password}</Text>
<Button onPress={handleSubmit} title="Submit" />
</View>
);
};
export default App;