受控单选按钮警告,通过formik字段处理其价值

时间:2019-09-11 03:52:20

标签: reactjs radio-button material-ui formik

我创建了单选按钮,其值由Formik字段处理。这样我就可以在提交时使用其他formik字段输入值访问选定的单选按钮值,并且可以简单地重用单选按钮功能。

单选按钮起作用。单击提交按钮时,可以使用其他输入值获取该值。但我在下面收到警告消息。

Warning: Material-UI: A component is changing a controlled RadioGroup to be uncontrolled.
Input elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled RadioGroup element for the lifetime of the component.
    in RadioGroup (created by RadioButtonGroup)
    in RadioButtonGroup (created by FieldInner)
    in FieldInner (created by Context.Consumer)
    in Context.Consumer (created by FormikConnect(FieldInner))
    in FormikConnect(FieldInner) (created by BankAccountOptions)
    in BankAccountOptions (created by EditUserForm)
    in EditUserForm (created by Formik)
    in Formik (created by DeleteUserFormBox)
...

我认为我需要找到一种方法来处理“选中的”道具,并确保它具有真实的||。错误的布尔值。 我试图通过RadioButtonGroup组件中的'setFieldValue'onChange手动控制道具。但是我只能从那里访问值。

Please Click here to see my code sample.

单击indexPage中的“单选按钮”链接将带您进入示例页面。您可以在用户和共享文件夹中找到相关代码。

谢谢!!

1 个答案:

答案 0 :(得分:0)

我在“ RadioGroup ”中添加了“ ”道具,错误消息现在消失了。

const RadioButtonGroup = ({
  field: { onChange, name, value, ...rest },
  form: { errors, touched, setFieldValue },
  ...props
}) => {
  const errorMessage = getIn(errors, name);
  const isTouched = getIn(touched, name);

  const change = (e, name, shouldValidate) => {
    e.persist();
    const inputValue = e.target.value;
    return setFieldValue(name, inputValue, shouldValidate);
  };

  return (
    <React.Fragment>
      <RadioGroup
        id="radioGroup"
        value={value || ''}
        onChange={e => change(e, name, true)}
        {...rest}
        {...props}
        row
      />
      <p style={styles}>{isTouched && errorMessage}</p>
    </React.Fragment>
  );
};

export default RadioButtonGroup;

```