react-final-form字段的动态名称

时间:2019-05-31 22:40:39

标签: react-final-form

我有2种表格。当我在第一种形式上选择一个选项时,第二种形式将使用从后端检索的参数添加到页面中。现在如何将参数名称设置为react-final-form字段名称?

我找不到解决办法。在哪里传递参数名称?

  <Form
    onSubmit={onSubmit}
    validate={validate}

2 个答案:

答案 0 :(得分:0)

React Final Form使用表单中所有字段的值调用onSubmit函数。将值传输到服务器完全取决于您。

如果您询问如何构建第二个表单,则只需添加需要添加的字段。因此,假设您从服务器回来时需要三个字段:[ 'name', 'startTime', 'endTime' ]。您只需遍历该数组并添加字段。

<Form onSubmit={onSubmit}>({handleSubmit}) => (
  <form onSubmit={handleSubmit}>
    {fieldsFromServer.map(fieldName => (
      <div key={fieldName}>
        <label>{fieldName}</label>
        <Field name={fieldName} component="input"/>
      </div>
    ))}
  </form>
)}<Form>

有帮助吗?您不必“将参数传递给表单”,只需添加所需的Field组件。

答案 1 :(得分:0)

像这样调用FinalForm

<FinalFieldArrayForm onSubmit={this.handleSubmitTemplate} fieldsFromServer={parameters} />

而FinalForm是

import React from "react";
import ReactDOM from "react-dom";
import { Form, Field } from 'react-final-form'
import arrayMutators from 'final-form-arrays'
import { FieldArray } from 'react-final-form-arrays'

import "./styles.css";

const FinalForm = ({onSubmit, fieldsFromServer}) => (
  <Form
    onSubmit={onSubmit}
    mutators={{
      // potentially other mutators could be merged here
      ...arrayMutators
    }}
    render={({
      handleSubmit,
      form: {
        mutators: { push, pop }
      },
      pristine,
      form,
      submitting,
      values
    }) => (
      <form onSubmit={handleSubmit}>
        <div className="buttons">
          <button type="button" onClick={() => push('records', undefined)}>+</button>
          <button type="button" onClick={() => pop('records')}>-</button>
          <button type="button" onClick={form.reset} disabled={submitting || pristine}>Reset</button>
        </div>
        <FieldArray name="records">
        { ({fields}) => (
          <div>
          {fields.map( (name, index) => (
            <div key={`${name}.${index}`}>
              <label>{index + 1}</label>
              {fieldsFromServer.map( param => <Field key={`${name}.${param}`} name={`${name}.${param}`} component="input" placeholder={`${name}.${param}`} /> )}
              <button type="button" onClick={() => fields.remove(index)}>-</button>
              <button type="button" onClick={() => fields.insert(index+1)}>+</button>
            </div>
          ))}
          </div>
        )}
        </FieldArray>
        <div className="buttons">
          <button type="submit" disabled={submitting || pristine}>Submit</button>
        </div>
        <pre>{JSON.stringify(values, 0, 2)}</pre>
      </form>
    )}
  />
)

const rootElement = document.getElementById("root");
ReactDOM.render(<FinalForm onSubmit={() => (<div/>)} fieldsFromServer={["firstName", "lastName"]} />, rootElement);