M. *_*Yal 5 validation typescript reactjs yup formik
我有一个动态表单,可以使用 formik 的 fieldarray 创建。我没有问题生成新的表单字段并验证它们。我正在使用打字稿,下面的代码在错误字段上显示类型错误。
<Formik
enableReinitialize
initialValues={{
formValues: [
{
socialPlatform: "",
url: "",
},
],
}}
onSubmit={(values) => {
console.log(values);
}}
validationSchema={validationSchema}
>
{({ values, handleChange, errors, touched }) => {
return (
<Form>
<FieldArray name="formValues">
{({ push }) => (
<React.Fragment>
{values.formValues.map((formValue, index) => (
<Field
id={`formValues.${index}.socialPlatform`}
name={`formValues.${index}.socialPlatform`}
label="Social Platform"
placeholder="Select Social Media"
options={socialMedias}
value={formValue.socialPlatform}
onChangeHandler={handleChange}
hasError={
errors.formValues[index].socialPlatform &&
touched.formValues[index].socialPlatform
}
errorMessage={errors.formValues[index].socialPlatform}
component={Dropdown}
/>
))}
</React.Fragment>
)}
</FieldArray>
</Form>
);
}}
</Formik>
Run Code Online (Sandbox Code Playgroud)
下面的部分显示对象可能是“未定义”并且属性“socialPlatform”在类型“string |”上不存在。FormikErrors<{ 社交平台:字符串;网址:字符串;}>'。类型“string”上不存在属性“socialPlatform”。我应该怎么办?
hasError={
errors.formValues[index].socialPlatform &&
touched.formValues[index].socialPlatform
}
errorMessage={errors.formValues[index].socialPlatform}
Run Code Online (Sandbox Code Playgroud)
编辑:好吧,因为我找不到任何关于这个问题的有意义的内容,所以我必须将 Touched 和 Errors 属性传递给输入组件,并使用 Formik 的 getIn 函数处理验证,如下所示;
<Field
id={`formValues.${index}.socialPlatform`}
name={`formValues.${index}.socialPlatform`}
label="Social Platform"
placeholder="Select Social Media"
options={socialMedias}
value={formValue.socialPlatform}
onChangeHandler={handleChange}
handleError={errors}
handleTouched={touched}
component={Input}
/>
Run Code Online (Sandbox Code Playgroud)
然后在输入组件内;
import { getIn } from "formik";
const errorMessage = FormikError(handleError, handleTouched, name);
const FormikError = (errors: any, touched: any, fieldName: any) => {
const error = getIn(errors, fieldName);
const touch = getIn(touched, fieldName);
return touch && error ? error : null;
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1412 次 |
最近记录: |