React Native中使用Yup与Formik做表单校验时错误提示不更新如何解决
问题排查结果
你当前代码的核心问题是输入框没有和Formik的状态做双向绑定,输入内容变更时Formik无法感知到数值变化,自然不会触发Yup校验,错误提示也就不会更新。
具体修改步骤
1. 补充解构Formik提供的values属性
你在Formik的render回调参数中漏了解构values,无法将最新的表单值同步到输入框展示。
2. 给自定义AppTextInput绑定变更事件和值
给两个输入框分别加上onChangeText绑定Formik的handleChange方法,同时绑定value属性实现双向同步,输入内容变更时Formik就会自动触发校验逻辑。
修改后的核心代码如下:
<Formik initialValues={{ email: "", password: "" }} onSubmit={(values) => console.log(values)} validationSchema={validationSchema} > {/* 补充解构values */} {({ handleChange, handleSubmit, errors, setFieldTouched, touched, values }) => ( <> <AppTextInput autoCapitalize="none" autoCorrect={false} icon="email" keyboardType="email-address" onBlur={() => setFieldTouched("email")} {/* 新增绑定 */} onChangeText={handleChange("email")} value={values.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")} {/* 新增绑定 */} onChangeText={handleChange("password")} value={values.password} secureTextEntry textContentType="password" /> <ErrorMessage visible={touched.password} error={errors.password} /> <AppButton onPress={handleSubmit} title="Login" /> </> )} </Formik>
额外排查项
如果修改后还是不生效,可以做如下检查:
- 确认你的自定义
AppTextInput组件正确接收了value和onChangeText属性,并传递给了内部的React Native原生TextInput组件 - 确认
ErrorMessage组件的visible逻辑正确:当visible为true且error有值时才显示错误文本 - 密码校验的文案拼写有误,可以把
To short改成Too short
内容的提问来源于stack exchange,提问作者Web Builders
相关产品推荐
相关产品推荐

