Redux表单:根据字段值显示自定义组件

时间:2017-04-25 04:23:08

标签: reactjs redux react-redux redux-form react-toolbox

我有一个FieldArray:

<FieldArray name="elements" component={renderFiles}/>

数据:

[
  {name:'xxx', url:'www.xxx.com', isRepeat: true},
  {name:'yyy', url:'', isRepeat: false},
  {name:'zzz', url:'', isRepeat: false}
]

我需要显示SwitchField,具体取决于网址

const renderFiles = ({ fields }) => {
   return (
      <div>
        {fields.map((element, index) =>
          <div key={'preview-wrap-'+index}>
            <Field
              name={`${element}.name`}
              type="text"
              component={TextField}/>
            { element.url ? 
              <Field 
              name={`${element}.isRepeat`} 
              component={SwitchField} 
              change={() => { console.log('change')}}/> :
              '' 
            }
        </div>
      )}
    </div>
  )
}

TextField和SwitchField是react-toolbox的自定义组件:

const TextField = ({ input, label, theme, meta: { touched, error }, ...custom }) => (
  <Input type='text' label={label} error={touched ? error : ''} {...input} {...custom} theme={{error:'text-error', ...theme}} />
)

const SwitchField = ({ input, label }) => (
  <Switch checked={!!input.value} label={label} onChange={(value) => {console.log('change')}} {...input} />
)

1 个答案:

答案 0 :(得分:0)

我可能没有清楚地理解你的问题,因为它相当简单但不是:

{ element.url ? <Field component={SwitchField} .../> : "" }

你可以这样做:

{ 
element.url 
  ? <Field component={SwitchField} .../>
  : <Field component={TextField} .../>
}