4

我有一个复杂的表单,其中某些字段的可见性取决于其他字段的值。如何根据 redux-form 中的其他字段的值设置字段的可见性?

const renderField = ({ input, label, type, display='flex',  meta: { touched, error } }) => (
    <div style={ { display: display }}>
      <label>{label}</label>
      <div>
        <input {...input} type={type} placeholder={label}/>
        {touched && error && <span>{error}</span>}
      </div>
    </div>
)



const renderMembers = ({ fields, meta: { touched, error } }) => (
  <ul>
    <li>
      <button type="button" onClick={() => fields.push({})}>Add Member</button>
      {touched && error && <span>{error}</span>}
    </li>
    {fields.map((member, index) =>
      <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"/>
        <Fields names={[ `${member}.firstName`, `${member}.lastName` ]} component={renderFields}/>
        <FieldArray name={`${member}.hobbies`} component={renderHobbies}/>
      </li>
    )}
  </ul>
)
4

1 回答 1

2

假设您有一个包含 2 个字段的表单:

const fields = [
  'foo',
  'bar'
]
reduxForm(
{
  form: 'AwesomeForm',
  fields
}
)(AwesomeForm) 

要根据组件中的其他字段值控制字段的可见性,您可以使用内联样式<AwesomeForm/>设置相应的值。display只需进行验证,检查其他值是否满足所需条件。喜欢:

export const AwesomeForm = (props) => {
  return (
    <form onSubmit={props.handleSubmit}>
      <TextField
        {...props.fields.foo}     
      />
      <TextField
        {...props.fields.bar}
        style={{
          display: props.fields.name.foo === 'some value' ? 'none' : 'block',
        }}
      />

      <button
        type='submit'
        />

    </form>

  )
}
于 2016-10-07T07:56:12.413 回答