FormSection和Fields之间有什么区别

时间:2017-03-17 13:35:15

标签: reactjs redux-form

redux-form的FormSection和Fields组件之间有什么区别。何时使用哪一个?

2 个答案:

答案 0 :(得分:1)

FormSection组件将表单拆分为更小的组件,就像HTML中的一节一样。

字段基本上是表单中的最小元素(任何输入),您可以通过传递开箱即用的组件或使用任何自定义来自定义任何字段。

每个Field都将通过form-reducer连接到redux商店。

在一个非常基本的形式中,您只需要使用Fields和FormSections根本不是必需的,请查看redux-forms文档中的simplest示例。

答案 1 :(得分:0)

Fields

它与Field类似,但您同时使用多个字段 如果您希望在与A交互时访问B之一的状态,则非常有用;例如:

const CitySelection = ({ state, city }) => (
  <div>
    {/* Whenever the state is changed, the city value is reset */}
    <select { ...state.input } onChange={event => {
      state.input.onChange( event );
      city.input.onChange( null );
    }}>
      <option>Choose your state</option>
    </select>
    <select { ...city.input }></select>
  </div>
);

<Fields names={[ "state", "city" ]} component={ CitySelection } />

请注意,从v6.5.0起,它相当有限。 Field允许您传递事件处理程序(onChangeonBlur等),内联验证程序等。Fields不要。

请注意Fields可能会导致性能问题。这是因为整个组件重新呈现在一起。

老实说,使用Redux Form 6个月后我从未需要使用Fields。如果您找到合理的理由,请告诉我,以便我可以改进这个答案!

FormSection

它允许您将表单的某些部分拆分为较小的组件,以高级方式。 与Fields不同,您不会处理低级inputmeta道具。因此,如果您想了解同一部分中其他字段的状态,则需要将其连接到Redux存储。

另一个区别是FormSection中的字段继承了节名称作为字段名称前缀。

const Address = () => (
  <div>
    <Field name="state" component="select" />
    <Field name="city" component="select" />
  </div>
);

<FormSection name="homeAddress" component={ Address } />
<FormSection name="workAddress" component={ Address } />

在这种情况下,您的表单将包含值homeAddress.cityhomeAddress.stateworkAddress.cityworkAddress.state