【问题标题】:formik ui validation for material ui react radion buttonsformik ui 验证材料 ui 反应单选按钮
【发布时间】:2021-01-09 07:00:01
【问题描述】:

我正在尝试将 formik 包裹在材料 ui 反应表单组件周围。它适用于 TextField 组件。请在下面找到代码:

<TextField
              id="firstName"
              name="firstName"
              label="First Name"
              variant="outlined"
              autoComplete="off"
              value={formik.values.firstName}
              onChange={formik.handleChange}
              error={
                formik.touched.firstName && Boolean(formik.errors.firstName)
              }
              helperText={formik.touched.firstName && formik.errors.firstName}
              className={classes.controls}
            />

但是如何将它包裹在单选按钮周围:

<FormControl component="fieldset" className={classes.controls}>
              <FormLabel component="legend">Gender</FormLabel>
              <RadioGroup aria-label="gender" name="gender">
                <FormControlLabel
                  value="male"
                  control={<Radio />}
                  label="Male"
                />
                <FormControlLabel
                  value="female"
                  control={<Radio />}
                  label="Female"
                />
              </RadioGroup>
            </FormControl>

找不到足够的文档来修复该位。谁能帮忙。

谢谢

【问题讨论】:

  • 你能提供一个codeandbox或者你的代码吗?同时这可能会有所帮助:您的控制组件可能会收到onChange 属性。 &lt;FormControlLabel control={&lt;Checkbox checked={apple} onChange={handleChange} name="apple" /&gt;} label="Apple" /&gt;

标签: reactjs material-ui radio-button formik radio-group


【解决方案1】:

我执行以下操作来实现单选组按钮:

import { FormControlLabel, Radio } from "@material-ui/core";
import * as yup from "yup";

export function RadioButtonGroup(props) {
  const [field] = useField({
    name: props.name,
    type: "radio",
    value: props.value,
  });
  return (
    <FormControlLabel
      control={<Radio {...props} {...field} />}
      label={props.label}
    />
  );
}

在表单中添加以下代码:

      <RadioButtonGroup name="gender" value="male" label="Male" />
      <RadioButtonGroup name="gender" value="female" label="Female" />

用于验证:

const validationSchema = yup.object({
  gender: yup.string().required("Gender is required"),
});

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2018-11-08
    相关资源
    最近更新 更多