FormSection 和 Fields 有什么区别

What is the difference between FormSection and Fields

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

FormSection 组件将表单拆分成更小的组件,就像 HTML 中的一个部分。

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

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

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

Fields

它类似于 Field,但您可以同时处理多个字段。
如果您想在与 B 交互时访问 A 之一的状态,这将很有用;例如:

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