javascript - React - Formik - 字段数组 - 实现可重复的表单字段
问题描述
我正在尝试遵循有关使用FieldArrays的 Formik 文档,以便可以将可重复的表单元素添加到我的表单中。
我还看到这个Medium 帖子举了一个例子。
我学得很慢,无法连接文档和实现之间的点。
我想在我的主表单中有一个按钮,上面写着:“添加数据请求”。
如果选择了该按钮,则会显示设置数据配置文件的嵌套表单,以及“添加另一个数据请求”和“删除”按钮。
我已经在我的应用程序的另一个组件中制作了嵌套表单,但我正在努力弄清楚如何使用中篇文章中的示例来合并嵌套表单(作为可重复的元素 - 即有人可能需要 5 个数据请求)。
有没有关于如何实现这一点的例子?
在我的代码中,我基本上遵循了中号帖子,但尝试将数据请求表单组件链接到索引内
<button
type="button"
onClick={() => arrayHelpers.insert(index, <DataRequestForm />)}>
Add a data request
</button>
这显然是不正确的,但我无法掌握如何做到这一点。
接受 Nithin 的回答,我尝试修改嵌入式表单,以便我可以使用 react-select,如下所示,但我收到一个错误消息:
TypeError:无法读取未定义的属性“值”
import React from "react";
import { Formik, Form, Field, FieldArray, ErrorMessage, withFormik } from "formik";
import Select from "react-select";
import {
Button,
Col,
FormControl,
FormGroup,
FormLabel,
InputGroup,
Table,
Row,
Container
} from "react-bootstrap";
const initialValues = {
dataType: "",
title: "",
description: '',
source: '',
}
class DataRequests extends React.Component {
render() {
const dataTypes = [
{ value: "primary", label: "Primary (raw) data sought" },
{ value: "secondary", label: "Secondary data sought"},
{ value: "either", label: "Either primary or secondary data sought"},
{ value: "both", label: "Both primary and secondary data sought"}
]
return(
<Formik
initialValues={initialValues}
render={({
form,
remove,
push,
errors,
status,
touched,
setFieldValue,
setFieldTouched,
handleSubmit,
isSubmitting,
dirty,
values
}) => {
return (
<div>
{form.values.dataRequests.map((_notneeded, index) => {
return (
<div key={index}>
<Table responsive>
<tbody>
<tr>
<td>
<div className="form-group">
<label htmlFor="dataRequestsTitle">Title</label>
<Field
name={`dataRequests.${index}.title`}
placeholder="Add a title"
className={"form-control"}
>
</Field>
</div>
</td>
</tr>
<tr>
<td>
<div className="form-group">
<label htmlFor="dataRequestsDescription">Description</label>
<Field
name={`dataRequests.${index}.description`}
component="textarea"
rows="10"
placeholder="Describe the data you're looking to use"
className={
"form-control"}
>
</Field>
</div>
</td>
</tr>
<tr>
<td>
<div className="form-group">
<label htmlFor="dataRequestsSource">Do you know who or what sort of entity may have this data?</label>
<Field
name={`dataRequests.${index}.source`}
component="textarea"
rows="10"
placeholder="Leave blank and skip ahead if you don't"
className={
"form-control"}
>
</Field>
</div>
</td>
</tr>
<tr>
<td>
<div className="form-group">
<label htmlFor="dataType">
Are you looking for primary (raw) data or secondary data?
</label>
<Select
key={`my_unique_select_keydataType`}
name={`dataRequests.${index}.source`}
className={
"react-select-container"
}
classNamePrefix="react-select"
value={values.dataTypes}
onChange={selectedOptions => {
// Setting field value - name of the field and values chosen.
setFieldValue("dataType", selectedOptions)}
}
onBlur={setFieldTouched}
options={dataTypes}
/>
</div>
</td>
</tr>
<tr>
<Button variant='outline-primary' size="sm" onClick={() => remove(index)}>
Remove
</Button>
</tr>
</tbody>
</Table>
</div>
);
})}
<Button
variant='primary' size="sm"
onClick={() => push({ requestField1: "", requestField2: "" })}
>
Add Data Request
</Button>
</div>
)
}
}
/>
);
};
};
export default DataRequests;
解决方案
您不能在表单元素内添加嵌套表单。有关模式的详细信息,请参阅下面的帖子。
如果您希望在主窗体内使用嵌套结构嵌套多个字段,您可以使用FieldArrays
.
您可以像这样构造表单。
{
firstName: "",
lastName: "",
dataRequests: []
}
这里firstName
和lastName
是顶级表单字段,dataRequests
可以是一个数组,其中每个元素都遵循结构
{
requestField1: "",
requestField2: ""
}
由于dataRequests
是一个数组,因此要渲染每个项目,FieldArray
您需要一个 map 函数。
form.values.dataRequests.map( render function() )
对于每个呈现的项目,更改处理程序应该以它们的索引为目标,以更新FieldArray
.
<div key={index}>
<Field
name={`dataRequests.${index}.requestField1`}
placeholder="requestField1"
></Field>
<Field
name={`dataRequests.${index}.requestField2`}
placeholder="requestField2"
></Field>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
在上面的代码片段中,name={dataRequests.${index}.requestField1}
要求 formik用输入字段的值更新数组元素的键requestField1
。nth
dataRequests
最后,您的<DataRequest />
组件可能如下所示。
import React from "react";
import { Field } from "formik";
export default ({ form, remove, push }) => {
return (
<div>
{form.values.dataRequests.map((_notneeded, index) => {
return (
<div key={index}>
<Field
name={`dataRequests.${index}.requestField1`}
placeholder="requestField1"
></Field>
<Field
name={`dataRequests.${index}.requestField2`}
placeholder="requestField2"
></Field>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
);
})}
<button
type="button"
onClick={() => push({ requestField1: "", requestField2: "" })}
>
Add Data Request
</button>
</div>
);
};
并使用<FieldArray />
您可以连接<DataRequest />
到主窗体。
您可以尝试以下示例 SO 片段
function DataRequests({ form, remove, push }){
return (
<div>
{form.values.dataRequests.map((_notneeded, index) => {
return (
<div key={index}>
<Formik.Field
name={`dataRequests.${index}.requestField1`}
placeholder="requestField1"
></Formik.Field>
<Formik.Field
name={`dataRequests.${index}.requestField2`}
placeholder="requestField2"
></Formik.Field>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
);
})}
<button
type="button"
onClick={() => push({ requestField1: "", requestField2: "" })}
>
Add Data Request
</button>
</div>
);
};
class Home extends React.Component {
initialValues = {
firstName: "",
lastName: "",
dataRequests: []
};
state = {};
render() {
return (
<div>
<Formik.Formik
initialValues={this.initialValues}
onSubmit={values => {
this.setState({ formData: values });
}}
>
{() => {
return (
<Formik.Form>
<div>
<Formik.Field
name="firstName"
placeholder="First Name"
></Formik.Field>
</div>
<div>
<Formik.Field
name="lastName"
placeholder="Last Name"
></Formik.Field>
</div>
<Formik.FieldArray name="dataRequests" component={DataRequests} />
<button type="submit">Submit</button>
</Formik.Form>
);
}}
</Formik.Formik>
{this.state.formData ? (
<code>{JSON.stringify(this.state.formData, null, 4)}</code>
) : null}
</div>
);
}
}
ReactDOM.render(<Home />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/formik/dist/formik.umd.production.js"></script>
<div id="root"></div>
推荐阅读
- laravel - Laravel Queue 队列:在共享主机后台运行的工作(CPanel)
- go - 检测符号链接
- python - 以错误的间隔或格式为输入引发异常
- python - Countplot 函数不适用于分箱数据
- java - Spring AMQP - 应用程序启动时未创建 RabbitMQ 连接
- python - Python:使用单一调度函数的官方指南
- git - 使用变基进行壁球期间丢失的更改
- javascript - 如何从控制台访问 iframe 元素并避免权限被拒绝的跨域对象
- xamarin - 类似元素的 Xamarin UItest 查询
- java - 使用 Java14 在 JavaFX 中播放 Media/AudioClip