如何在ReactJS中以Formik形式的初始值设置预场数据

时间:2019-12-07 06:37:06

标签: reactjs formik

我正在使用react js中的map函数创建一个Formik表单,但我也想从该状态填充初始数据。我可以通过设置初始值(如以下代码)以静态形式使用它

       <Formik
        initialValues={{
          firstName: Data.firstName,
          lastName: Data.lastName,
        }}
        validationSchema={SignupSchema}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            console.log("inside form", values);
            this.updateForm(values);
            setSubmitting(false);
          }, 400);
      }}>

所以,如果我像下面的代码那样创建输入内容,该怎么办

    const masterCategory = Object.keys(campaignObj.newMasterCategory).map(item => {
     return (
       <Field name={`master_category${fc}`} key={fc}>
         {({ field }) => <input {...field} className="form-control nopadding-r input-width" type="text" placeholder="Enter Master Category" />}
      </Field>
    );

  });

并像这样渲染它

      <div className={`col-6 ${this.state.retailflag}`}>
          {masterCategory}
      </div>

1 个答案:

答案 0 :(得分:0)

对我有用。

import React, { Component } from "react";
import { Formik, Field } from "formik";

export default class Form extends Component {
  formlist = ["username", "password"];

  render() {
    return (
      <Formik
        initialValues={{ username: "", password: "" }}
        onSubmit={this.props.handleSubmit}
        {...this.props}
      >
        {formikProps => {
          return (
            <ul>
              {this.formlist.map((item, i) => {
                return (
                  <li key={i}>
                    <Field type="email" name={item} placeholder="Email" />
                  </li>
                );
              })}
              <li>
                <button type="submit" onClick={formikProps.handleSubmit}>
                  Login
                </button>
              </li>
            </ul>
          );
        }}
      </Formik>
    );
  }
}
<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>

示例=> https://codesandbox.io/s/empty-monad-obfvx