简体   繁体   中英

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

I have a scenario where there will be two fields of each item. One field is a checkbox and another is dropdown but the point is to get a pair of data from this and I am mapping this based on the item(they have category too). And the dropdown depends on checkbox(when unchecked the dropdown is disabled and value is reset to none or zero)

I tried

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

what happens is each of them have unique name and I cant do anything when I need to update the values depending on the checkbox selections. I have tried putting the two inputs in one Field but I can't get it to work. Help would be much appreciated

You need to use Redux Fields ( https://redux-form.com/6.0.4/docs/api/fields.md/ ) not Redux Field.
You can create a separate component which wraps your check-box component and your drop-down component.

This is how you use it

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

And the props that you get in your MyMultiFieldComponent

{
  checkboxFieldName: { input: { ... }, meta: { ... } },
  dropDownFieldName: { input: { ... }, meta: { ... } },
  anotherCustomProp: 'Some other information'
}

The input property has a onChange property (which is a method), you can call it to update the respective field value.

For example in onChange method of check-box

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');
  }
}

This way you can update multiple field values at the same time.

Hope this helps.

Probably, this is what are you looking for - formValues decorator.

Just wrap your dropdown with this decorator and pass the name into it of your checkbox so you will have access inside of the MyDropDownComponent .

For example:

import { formValues } from 'redux-form';

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

So then myCheckBox value will be passed as a prop.

Performance note:

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

Use this sparingly.

See more here - https://redux-form.com/7.3.0/docs/api/formvalues.md/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM