如何在Redux中使用Normalize - 表单字段组件

时间:2017-09-27 02:55:27

标签: reactjs redux-form

我对Redux表单有疑问

https://redux-form.com/7.0.4/examples/normalizing/ - 这一个

我将两个输入与Fields组件组合在一起,在每个输入中我想使用Redux-Form中的Normalize方法,我该怎么做?

示例:

<Fields 
  names={[ 'first', 'last' ]} 
  component={this.renderFields}
/>

const renderFields = (fields) => (
 <div>
  <input {...fields.first.input}>
  <input {...fields.first.input}>
 </div>
)

2 个答案:

答案 0 :(得分:1)

我认为您必须手动运行规范化功能:

const renderFields = (fields) => {
  const first = fields.first;
  const onChangeFirst = (event) => {
     const newValue = event.target.value;
     // normalize is passed down as a prop as well
     const normalizedValue = fields.normalize(newValue);
     // pass the normalized value to the Redux-Form onChange
     first.input.onChange(normalizedValue);
  };

  const last = fields.last;
  // do the equivalent thing for "last"
  // const onChangeLast  .... ...

  return (
     <div>
       <input {...first.input} onChange={ onChangeFirst }>
       <input {...last.input} onChange={ onChangeLast } >
     </div>
  );
}

然后你会像

一样使用它
<Fields 
  names={ [ 'first', 'last' ] } 
  component={ this.renderFields }
  normalize={ myNormalizeFunction }
/>

您可以看到有效的JSFiddle demo here

答案 1 :(得分:0)

<Fields 
  names={ [ 'first', 'last' ] } 
  component={ this.renderFields }
  format={ (name, value) => {
    if(name === 'first') {
       //return something for [first value] like normalize function
    }
    //return something for [last value] like normalize function
  }}
/>