带有嵌套输入字段的React Hook表单

时间:2020-07-08 04:21:36

标签: javascript reactjs react-hook-form

摘要: 嵌套在另一个组中的单选按钮组会更新父组的值

详细信息: 我正在使用Form Context并将控件传递给每个输入 为了显示,我需要将一个广播组放在另一个广播组中,创建一个嵌套的广播组:

const watchParentGroup = methods.watch('ParentGroup');
...
<RadioGroup controllerName="ParentGroup">
    <RadioButton value="1" name="ParentGroup" style={{ marginRight: 15 }}>
        <span>I am parent's button</span>
        {parseInt(watchParentGroup, 10) === 1 && (
            <RadioGroup controllerName="ChildGroup">
                <RadioButton value="a" name="ChildGroup" style={{ marginRight: 15 }}>
                    <span>I am child's button</span>
                </RadioButton>
            </RadioGroup>
        )}
    </RadioButton>
    ...
</RadioGroup>

这是RadioButton和RadioGroup:

import { Controller, useFormContext } from 'react-hook-form';
import React from 'react';
import { Radio, useRadioState, RadioGroup as PrettyRadioGroup } from 'pretty-checkbox-react';

const RadioGroup = ({ children }) => {
  const radio = useRadioState();

  const radios = React.Children.map(children, (child) => {
    return React.cloneElement(child, { radio });
  });

  return (
    <div>
      <PrettyRadioGroup {...radio}>{radios}</PrettyRadioGroup>
    </div>
  );
};

const RadioButton = ({ radio, name, value, children, style }) => {
  const { control } = useFormContext();
  return (
    <Controller
      as={(
        <label style={style}>
          <Radio value={value} name={name} {...radio} />
          {children}
        </label>
      )}
      name={name}
      control={control}
    />
  );
};

假设我单击父组的第一个按钮,watchParentGroup结果为1,子组将呈现。但是,当我单击子项的选项时,watchParentGroup也会更新为“ a”,并且因此将子项组删除。

我应该如何设置表格,以使ChildGroup不会影响ParentGroup的价值?

0 个答案:

没有答案