问题描述
我正在学习如何使用 yup 验证,这是我的代码。 但验证错误消息不会改变。
import React from "react";
import { StyleSheet,Image } from "react-native";
import * as Yup from "yup";
import { Formik } from "formik";
import AppTextInput from "../components/AppTextInput";
import Screen from "../components/Screen";
import AppButton from "../components/AppButton";
import ErrorMessage from "../components/ErrorMessage";
const validationSchema = Yup.object().shape({
email: Yup.string().required().email("Please enter a valid email").label("Email"),password: Yup.string().required().min(4,"To short").label("Password"),});
function LoginScreen() {
return (
<Screen style={styles.container}>
<Image style={styles.logo} source={require("../assets/logo-red.png")} />
<Formik
initialValues={{ email: "",password: "" }}
onSubmit={(values) => console.log(values)}
validationSchema={validationSchema}
>
{({ handleChange,handleSubmit,errors,setFieldTouched,touched }) => (
<>
<AppTextInput
autoCapitalize="none"
autoCorrect={false}
icon="email"
keyboardType="email-address"
onBlur={() => setFieldTouched("email")}
name="email"
placeholder="Email"
textContentType="emailAddress"
/>
<ErrorMessage visible={touched.email} error={errors.email} />
<AppTextInput
autoCapitalize="none"
autoCorrect={false}
icon="lock"
name="password"
placeholder="Password"
onBlur={() => setFieldTouched("password")}
secureTextEntry
textContentType="password"
/>
<ErrorMessage visible={touched.password} error={errors.password} />
<AppButton onPress={handleSubmit} title="Login" />
</>
)}
</Formik>
</Screen>
);
}
const styles = StyleSheet.create({
container: {
padding: 10,},logo: {
width: 80,height: 80,alignSelf: "center",marginTop: 50,marginBottom: 20,});
export default LoginScreen;
解决方法
您没有编写 onChangeText
道具
像这样写两个AppTextInput
<AppTextInput
autoCapitalize="none"
autoCorrect={false}
onChangeText={handleChange('email')} // This was missing
icon="email"
keyboardType="email-address"
onBlur={() => setFieldTouched('email')}
name="email"
placeholder="Email"
textContentType="emailAddress"
/>
<AppTextInput
autoCapitalize="none"
autoCorrect={false}
onChangeText={handleChange('password')} // This was missing
icon="lock"
name="password"
placeholder="Password"
onBlur={() => setFieldTouched('password')}
secureTextEntry
textContentType="password"
/>