我如何动态地将我的表单绑定到Formik,在React功能组件



我正在构建一个React组件,它从外部API调用动态加载表单数据。我需要在用户完成后将其提交回另一个API端点。

在这里:

import React, { useEffect, useState } from "react";
import axios from "axios";
import TextField from "@material-ui/core/TextField";
import { useFormik } from "formik";
const FORM = () => {
const [form, setForm] = useState([]);
const [submission, setSubmission] = useState({});
const formik = useFormik({
initialValues: {
email: "",
},
});
useEffect(() => {
(async () => {
const formData = await axios.get("https://apicall.com/fakeendpoint");
setForm(formData.data);
})();  
}, []);
return (
<form>
{form.map((value, index) => {
if (value.fieldType === "text") {
return (
<TextField 
key={index} 
id={value.name}
label={value.label}
/>
);
} 
if (value.fieldType === "select") {
return (
<TextField 
select={true}
key={index} 
id={value.name}
label={value.label}
>
{value.options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</TextField>
);
}
})}
<button type="submit">Submit</button>
</form>
);
};

export default FORM;

API调用正在进入ok(是的,我现在需要一些错误处理),我能够填充字段并获得页面上的表单。我遇到麻烦的地方(我是Formik的新手,所以请原谅我)是我需要做验证和提交。我真的不知道如何处理这些值,通常我会为变量写一些静态代码,测试它们,然后提交。

通常我会设置一个"name"还有一个是"电子邮件"为例。在这种情况下,我不能写这些字段,因为它们来自API,我们不知道它们是什么,直到我们得到调用响应。

我的代码处理字段创建,但我需要连接验证和提交,并希望使用Formik。

如何完成动态表单(通过formik)连接验证和提交?

我有同样的问题,我用组件,而不是useFormik()钩子。不确定为什么useFormik在动态验证上失败,但无论如何,在切换到之后,下面是为我工作的代码。请在下面的代码片段后检查关键点。

<Formik
innerRef={formikRef}
initialValues={request || emptyRequest  //Mostafa: edit or new: if request state is avaialble then use it otherwise use emptyRequest.
}
enableReinitialize="true"
onSubmit={(values) => {
saveRequest(values);
}}
validate={(data) => {
let errors = {};
if (!data.categoryId) {
errors.categoryId = 'Request Category is required.';
}
//Mostafa: Dynamic validation => as the component is re-rendered, the validation is set again after request category is changed. React is interesting and a lot of repetitive work is done.
if (requestCategoryFields)
requestCategoryFields.map(rcField => {
if (rcField.fieldMandatory) { //1- check Mandatory
if (!data.dynamicAttrsMap[rcField.fieldPropertyName]) {
if (!errors.dynamicAttrsMap) //Mostafa: Need to initialize the object in errors, otherwise Formik will not work properly.
errors.dynamicAttrsMap = {}
errors.dynamicAttrsMap[rcField.fieldPropertyName] = rcField.fieldLabel + ' is required.';
}
}
if (rcField.validationRegex) { //2- check Regex
if (data.dynamicAttrsMap[rcField.fieldPropertyName]) {
var regex = new RegExp(rcField.validationRegex); //Using RegExp object for dynamic regex patterns.
if (!regex.test(data.dynamicAttrsMap[rcField.fieldPropertyName])) {
if (!errors.dynamicAttrsMap) //Mostafa: Need to initialize the object in errors, otherwise Formik will not work properly.
errors.dynamicAttrsMap = {}
if (errors.dynamicAttrsMap[rcField.fieldPropertyName]) //add an Line Feed if another errors line already exists, just for a readable multi-line message.
errors.dynamicAttrsMap[rcField.fieldPropertyName] += 'n';
errors.dynamicAttrsMap[rcField.fieldPropertyName] = rcField.validationFailedMessage; //Regex validaiton error and help is supposed to be already provided in Field defintion by admin user.
}
}
}
});
return errors;
}}>
{({errors,handleBlur,handleChange,handleSubmit,resetForm,setFieldValue,isSubmitting,isValid,dirty,touched,values
}) => (
<form autoComplete="off" noValidate onSubmit={handleSubmit} className="card">
<div className="grid p-fluid mt-2">
<div className="field col-12 lg:col-6 md:col-6">
<span className="p-float-label p-input-icon-right">
<Dropdown name="categoryId" id="categoryId" value={values.categoryId} onChange={e => { handleRequestCategoryChange(e, handleChange, setFieldValue) }}
filter showClear filterBy="name"
className={classNames({ 'p-invalid': isFormFieldValid(touched, errors, 'categoryId') })}
itemTemplate={requestCategoryItemTemplate} valueTemplate={selectedRequestCategoryValueTemplate}
options={requestCategories} optionLabel="name" optionValue="id" />
<label htmlFor="categoryId" className={classNames({ 'p-error': isFormFieldValid(touched, errors, 'categoryId') })}>Request Category*</label>
</span>
{getFormErrorMessage(touched, errors, 'siteId')}
</div>
{
//Here goes the dynamic fields
requestCategoryFields && requestCategoryFields.map(rcField => {
return (
<DynamicField field={rcField} values={values} touched={touched} errors={errors} handleBlur={handleBlur} 
handleChange={handleChange} isFormFieldValid={isFormFieldValid} getFormErrorMessage={getFormErrorMessage} 
crudService={qaCrudService} toast={toast} />
)
})
}
</div>
<div className="p-dialog-footer">
<Button type="button" label="Cancel" icon="pi pi-times" className="p-button p-component p-button-text"
onClick={() => {
resetForm();
hideDialog();
}} />
<Button type="submit" label="Save" icon="pi pi-check" className="p-button p-component p-button-text" />
</div>
</form>
)}

重点:

  1. 我的动态字段也来自远程API,通过选择categoryIdDropDown,并设置为requestCategoryFields状态。
  2. 我将动态字段的值存储在一个名为dynamicAttrsMap的嵌套对象中,该对象位于我的主对象中,称为request,因为我也有静态字段。
  3. 我使用validate道具,其中包括一个categoryId字段的静态验证,然后是一个循环(映射),为所有其他动态字段添加动态验证。此策略与每次状态更改一样工作,您的组件将被重新渲染,并且您的验证将从头创建。
  4. 我有两种验证,一种是检查强制字段的值是否存在。如果需要,另一个检查动态字段内容的正则表达式验证。
  5. 我将动态字段的渲染移动到一个单独的组件<DynamicField>,以便更好地模块化。请检查DynamicField组件
  6. 你可以移动验证道具到const更好的编码;这里我的代码有点乱。
  7. 我使用了两个const,为了更好的编码,错误信息和CSS如下:
const isFormFieldValid = (touched, errors, name) => { return Boolean(getIn(touched, name) && getIn(errors, name)) };
const getFormErrorMessage = (touched, errors, name) => {
return isFormFieldValid(touched, errors, name) && <small className="p-error">{getIn(errors, name)}</small>;
};

请检查我的完整组件在我的GitHub这里更好地理解。如果你需要澄清的话,请评论。因为我知道福米克有时有多狡猾。我们必须互相帮助。

添加enableReinitialize到formik

useFormik({
initialValues: initialData,
enableReinitialize: true,
onSubmit: values => {
// Do something
}
});

FORMIK医生

最新更新