如何在一个 redux-form Field 组件中关联多个组件?

How to associate multiple component in one redux-form Field component?

我有一个场景,每个项目都有两个字段。一个字段是一个复选框,另一个是下拉列表,但重点是从中获取一对数据,我正在根据项目映射它(它们也有类别)。并且下拉列表取决于复选框(未选中时下拉列表被禁用并且值重置为 none 或零)

我试过了

<Field name={ `${item.label}` } component={MyCheckBoxComponent}>
<Field name={ `${item.value}` } component={MyDropDownComponent}>

发生的情况是它们每个都有唯一的 name 并且当我需要根据复选框选择更新值时我无能为力。 我试过将两个输入放在一个 Field 中,但我无法让它工作。非常感谢帮助

可能,这就是您要找的 - formValues 装饰器。

只需用这个装饰器包装你的下拉菜单,并将名称传递给你的复选框,这样你就可以访问 MyDropDownComponent.

例如:

import { formValues } from 'redux-form';

<form ...>
    <Field name="myCheckBox" component={MyCheckBoxComponent}>
    <Field name="myDropdown" component={formValues('myCheckBox')(MyDropDownComponent)} />
</form>

那么 myCheckBox 值将作为 prop 传递。

性能说明:

This decorator causes the component to render() every time one of the selected values changes.

谨慎使用。

在这里查看更多 - https://redux-form.com/7.3.0/docs/api/formvalues.md/

您需要使用 Redux 字段 (https://redux-form.com/6.0.4/docs/api/fields.md/) 而不是 Redux 字段。
您可以创建一个单独的组件来包装您的 check-box 组件和 drop-down 组件。

这就是您的使用方式

<Fields 
  names={[ 
    checkboxFieldName,
    dropDownFieldName 
  ]}
  component={MyMultiFieldComponent}
  anotherCustomProp="Some other information"
/>

以及您在 MyMultiFieldComponent

中获得的道具
{
  checkboxFieldName: { input: { ... }, meta: { ... } },
  dropDownFieldName: { input: { ... }, meta: { ... } },
  anotherCustomProp: 'Some other information'
}

input属性有一个onChange属性(是一个方法),你可以调用它来更新各自的字段值。

例如在check-box

的onChange方法中
onChangeCheckbox (event) {
  const checked = event.target.checked;
  if (checked) {
    // write your code when checkbox is selected
  } else {
    const { checkboxFieldName, dropDownFieldName } = props;
    checkboxFieldName.input.onChange('Set it to something');
    dropDownFieldName.input.onChange('set to zero or none');
  }
}

这样您可以同时更新多个字段值。

希望对您有所帮助。