在使用React进行开发的时候,如果是简单的表单还好。如果遇到复杂的表单,比如分好几个步骤的表单,联动效果的字段,多层结构的字段等等,就需要一个好的框架的支持了。下面介绍一下如何在Formik中使用嵌套字段。

在Formik中使用嵌套对象
声明初始值
首先是在声明初始值的时候:
const initialValues = {
name: {
first: '',
last: ''
},
email: "",
age: 18,
};
使用
<Field
type="text"
id="first_name"
name="name.first"
/>
<ErrorMessage name='name.first'/>
<br />
在Formik中使用数组对象
声明初始值
const initialValues = {
name: {
first: '',
last: ''
},
email: "",
age: 18,
phone: ['', ''],
};
使用
<label htmlFor="phone1">first phone number</label>
<Field
type="text"
id="phone1"
name="phone[0]"
/>
<ErrorMessage name='phone[0]'/>
<br />