【发布时间】:2020-05-19 20:39:35
【问题描述】:
我一直在使用 Yup 和 Formik 在 React 中进行表单验证。 现在,当用户模糊输入时,会显示错误。 这是我的代码: 啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊!
import React from "react";
import { Formik, Field } from "formik";
import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
import * as yup from "yup";
const FirstNameInputComponent = ({ field, ...props }) => {
const { errorMessage, touched } = props;
const { name, value, onChange, onBlur } = field;
return (
<TextField
value={value}
name={name}
error={touched && errorMessage ? true : false}
label="نام"
helperText={touched && errorMessage ? errorMessage : undefined}
onChange={onChange}
onBlur={onBlur}
/>
);
};
const App = () => {
const validationSchema = yup.object().shape({
first_name: yup.string().required()
});
return (
<Formik
initialValues={{
file: undefined,
text: undefined
}}
validationSchema={validationSchema}
validateOnBlur={true}
render={({
values,
errors,
touched,
handleChange,
handleBlur,
setFieldValue
}) => {
return (
<form>
<Field
name="first_name"
component={FirstNameInputComponent}
errorMessage={errors["first_name"]}
touched={touched["first_name"]}
onChange={handleChange}
onBlur={handleBlur}
/>
</form>
/>
);
}
如何在用户输入输入的同时显示错误?
【问题讨论】:
-
它应该可以立即工作,
Formik组件上有一个 propvalidateOnChange,但默认情况下是这样。你能详细说明一下吗? -
@paolostyle 我做了
标签: javascript reactjs forms formik yup