React - Formik - 字段数组 - 实现可重复的表单字段

Mel*_*Mel 3 javascript reactjs formik

我正在尝试遵循有关使用FieldArrays的 Formik 文档,以便我可以将可重复的表单元素添加到我的表单中。

我还看到了这篇Medium 帖子给出了一个例子。

我学习很慢,无法将文档和实现之间的点联系起来。

我想在我的主表单中有一个按钮,上面写着:“添加数据请求”。

如果选择该按钮,则会显示设置数据配置文件的嵌套表单,以及“添加另一个数据请求”和“删除”按钮。

我已经在我的应用程序的另一个组件中创建了嵌套表单,但我正在努力弄清楚如何使用媒体帖子中的示例来合并嵌套表单(作为可重复元素 - 即有人可能需要 5 个数据请求)。

有没有关于如何实现这一点的例子?

在我的代码中,我基本上遵循了medium post,但尝试链接索引内的数据请求表单组件

<button 
      type="button"
      onClick={() => arrayHelpers.insert(index, <DataRequestForm />)}>
      Add a data request
</button>   
Run Code Online (Sandbox Code Playgroud)

这显然是不正确的,但我不知道如何做到这一点。

根据 Nithin 的回答,我尝试修改嵌入的表单,以便我可以使用 react-select,如下所示,但是我收到一个错误消息:

类型错误:无法读取未定义的属性“值”

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;
Run Code Online (Sandbox Code Playgroud)

Nit*_*mpi 7

您不能在表单元素中添加嵌套表单。有关模式的详细信息,请参阅以下帖子。

你能嵌套 html 表单吗?

如果您希望在主窗体中使用嵌套结构嵌套多个字段,则可以使用FieldArrays.

您可以像这样构造表单。

{
    firstName: "",
    lastName: "",
    dataRequests: []
  }
Run Code Online (Sandbox Code Playgroud)

这里firstNamelastName是顶级表单字段,dataRequests可以是一个数组,其中每个元素都遵循结构

{
  requestField1: "",
  requestField2: ""
}
Run Code Online (Sandbox Code Playgroud)

因为dataRequests是一个数组,所以为了渲染FieldArray你的每一项都需要一个 map 函数。

form.values.dataRequests.map( render function() )
Run Code Online (Sandbox Code Playgroud)

对于每个呈现的项目,更改处理程序应将其索引定位为更新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>
Run Code Online (Sandbox Code Playgroud)

在上面的代码中name={dataRequests.${index}.requestField1}要求formik更新了密钥requestField1nth的元件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>
  );
};
Run Code Online (Sandbox Code Playgroud)

并使用<FieldArray />您可以连接<DataRequest />到主窗体。

您可以尝试以下示例 SO 片段

{
    firstName: "",
    lastName: "",
    dataRequests: []
  }
Run Code Online (Sandbox Code Playgroud)
{
  requestField1: "",
  requestField2: ""
}
Run Code Online (Sandbox Code Playgroud)