简体   繁体   中英

Initializing dynamically created redux-form field

I have a redux-form Field which is dynamically created. For example, when I click on a button, I do a:

renderFormFields() {
 const r = someArray.map(s => {
   console.log(s.Value);
   return (<Field name={s.Name} type='number' component='input' min='1' {...s.Value} />);
 })

 {r}
}

render() {
 renderFormFields()
}

Now the console.log is printing the correct value for s.Value but the redux-form element is not having the correct value. The value is empty when the input Field is rendered. Any idea what I can do to initialize a redux-form Field when it is dynamically created ? (I cannot use the handleInitialize function approach that is mentioned in the documents as the form fields are dynamically generated at runtime)

您不应该传播s而不是s.value吗?

return (<Field name={s.Name} type='number' component='input' min='1' {...s} />);

Because you put s in string notation like this 's.Name'

You can put it like this {s.Name}

Field component doesn't contain value prop. You can set the default values using couple of options:

  1. initialValues (if you know the default values of fields that are going to be added dynamically)
  2. Use this.props.change (if default values are also dynamic)

Modifed version of SimpleForm example from redux-form:

import React from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm } from 'redux-form'

const extendedFields = [{ name: 'City', value: 'Hyderabad' }, { name: 'Phone', value: 2 }];

class SimpleForm extends React.Component {

  constructor() {
    super();
    this.state = {
      showExtended: false
    };
  }

  addExtendedFields() {
    // Not the best way to handle state. Doing this for simplicity
    this.setState({ showExtended: { initialized: false } });
  }

  renderExtendedFields() {
    const r = extendedFields.map(field => {
      return (
        <div key={field.name}>
          <label>{field.name}</label>
          <div>
            <Field type='text' component='input' {...field} value={field.value} />
          </div>
        </div>
      );
    });

    return r;
  }

  componentDidUpdate() {
    const { showExtended } = this.state;
    if (showExtended && !showExtended.initialized) {
      extendedFields.map(field => {
        this.props.change(field.name, field.value); // Option-2
        return field;
      });
      this.setState({ showExtended: { initialized: true } });
    }
  }

  render() {
    const { handleSubmit, pristine, reset, submitting } = this.props;
    const { showExtended } = this.state;
    return (
      <form onSubmit={handleSubmit}>
        <div>
          <label>First Name</label>
          <div>
            <Field name="firstName" component="input" type="text" placeholder="First Name" />
          </div>
        </div>
        <div>
          <label>Last Name</label>
          <div>
            <Field name="lastName" component="input" type="text" placeholder="Last Name" />
          </div>
        </div>
        <div>
          <label>Email</label>
          <div>
            <Field name="email" component="input" type="email" placeholder="Email" />
          </div>
        </div>
        <div>
          <label>Sex</label>
          <div>
            <label><Field name="sex" component="input" type="radio" value="male" /> Male</label>
            <label><Field name="sex" component="input" type="radio" value="female" /> Female</label>
          </div>
        </div>
        <div>
          <label>Favorite Color</label>
          <div>
            <Field name="favoriteColor" component="select">
              <option></option>
              <option value="ff0000">Red</option>
              <option value="00ff00">Green</option>
              <option value="0000ff">Blue</option>
            </Field>
          </div>
        </div>
        <div>
          <label htmlFor="employed">Employed</label>
          <div>
            <Field name="employed" id="employed" component="input" type="checkbox" />
          </div>
        </div>
        {showExtended && this.renderExtendedFields()}
        <div>
          <label>Notes</label>
          <div>
            <Field name="notes" component="textarea" />
          </div>
        </div>
        <div>
          <button type="submit" disabled={pristine || submitting}>Submit</button>
          <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
          <button type="button" onClick={this.addExtendedFields.bind(this)} disabled={showExtended}>Show Extended fields</button>
        </div>
      </form>
    );
  }
}

let HOCSimpleForm = reduxForm({
  form: 'simple'
})(SimpleForm);

HOCSimpleForm = connect(
  state => ({
    initialValues: { City: 'Test' } // Option-1
  })
)(HOCSimpleForm)

export default HOCSimpleForm;

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