无法使Material UI单选按钮与Formik一起使用 [英] Cannot get Material UI radio buttons to work with Formik

查看:339
本文介绍了无法使Material UI单选按钮与Formik一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Formik中使用材质UI"单选按钮,但单击不正确.我已将问题简化为以下示例: https://codesandbox.io/s/amazing -currying-s5vn0

I am trying to use Material UI radio buttons with Formik, and they are not clicking properly. I've reduced the problem to the following example: https://codesandbox.io/s/amazing-currying-s5vn0

如果有人知道我可能做错了什么,或者任何一个系统中都有错误,请告诉我.在以上示例中单击按钮时,它们不会保持单击状态.我有一个使用其他库组件的更复杂的react功能组件,所以我不能在这里包括它.它的行为略有不同:即使单击其他按钮,按钮仍保持单击状态.这可能是相同的问题,也可能不是相同的问题.预先感谢.

If anyone knows what I might be doing wrong, or if there is a bug in either system, then please let me know. When clicking on the buttons in the above example, they do not stay clicked. I have a more complex react functional component that uses other library components, so I cannot include it here. It is behaving a little differently: the buttons stay clicked even after clicking a different button. It may or may not be the same issue. Thanks in advance.

推荐答案

您需要在要作为Formik字段呈现的FormikRadioGroup组件内部呈现单选按钮.这样,您实际上可以将Formik管理的道具传递给要使用的组件,并允许RadioGroup组件确保一次只单击一个按钮.我添加了一个options道具,以提供一种传递单选选项的方法,并删除了您要在该组件外部渲染的所有元素:

You need to be rendering the radio buttons inside of the FormikRadioGroup component you are rendering as a Formik Field. That way you can actually pass the props being managed by Formik down to the components to be used, as well as allow the RadioGroup component to make sure only one button is clicked at a time. I added an options prop to provide a way to pass an array of radio options and removed all of the elements you were rendering outside of that component:

const FormikRadioGroup = ({
  field,
  form: { touched, errors },
  name,
  options,
  ...props
}) => {

  return (
    <React.Fragment>
      <RadioGroup {...field} {...props} name={name}>
        {options.map(option => (
          <FormControlLabel value={option} control={<Radio />} label={option} />
        ))}
      </RadioGroup>

      {touched[fieldName] && errors[fieldName] && (
        <React.Fragment>{errors[fieldName]}</React.Fragment>
      )}
    </React.Fragment>
  );
};

此处.

这篇关于无法使Material UI单选按钮与Formik一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆