简体   繁体   中英

Giving a default value to redux-form Field in a FieldArray when adding new Fields

It used to be in earlier versions of redux-form that you could pass an initialValue prop directly to a field as opposed to passing an initialValues value in your mapStateToProps function. Now it seems you can only do the latter.

I was wondering how I would set the default value of a newly pushed field in my field array to something like "Field No.2" (I would use the index passed to the field to get the number, I'm more stumped on how to pass the default value.)

You can pass the initial value when you push the new entry to your array. Given the example in the redux-form documentation:


const renderSubFields = (member, index, fields) => (
  <li key={index}>
    <button
      type="button"
      title="Remove Member"
      onClick={() => fields.remove(index)}
    />
    <h4>Member #{index + 1}</h4>
    <Field
      name={`${member}.firstName`}
      type="text"
      component={renderField}
      label="First Name"
    />
    <Field
      name={`${member}.lastName`}
      type="text"
      component={renderField}
      label="Last Name"
    />
  </li>
)
const renderMembers = ({ fields }) => (
  <ul>
    <button type="button" onClick={() => fields.push({ firstname: 'field 1 firstname', lastname: 'field 1 lastname' })}>
      Add Member
    </button>
    {fields.map(renderSubFields)}
  </ul>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM