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

时间:2019-10-13 01:22:46

标签: javascript reactjs formik

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

我也看到了这个Medium post的例子。

我学习缓慢,无法将文档和实现之间的点滴联系在一起。

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

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

我已经在应用程序的另一个组件中创建了嵌套表单,但是我正在努力从中间帖子中找出如何使用示例来合并嵌套表单(作为可重复元素-即某人可能需要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;

2 个答案:

答案 0 :(得分:3)

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

Can you nest html forms?

如果您希望在主窗体内嵌套具有嵌套结构的多个字段,则可以使用FieldArrays来实现。

您可以像这样构造表格。

{
    firstName: "",
    lastName: "",
    dataRequests: []
  }

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

{
  requestField1: "",
  requestField2: ""
}

由于dataRequests是一个数组,因此要渲染FieldArray的每个项目,您都需要一个地图函数。

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>

答案 1 :(得分:1)

对于希望从本文中学习的任何人,nithin对此问题的回答显然是出于良好的意愿,但这并不是对formik的正确部署。您可以在以下位置查看代码沙箱:https://codesandbox.io/embed/goofy-glade-lx65p?fontsize=14,以了解当前解决此问题的尝试(仍未解决),但朝着解决方案迈出了更好的一步。同样感谢您对这个问题的回答有帮助的意图。