reactjs React Hook Forms + Material UI Checkboxes + FormControlLabel未接收默认值

nvbavucw  于 2023-03-22  发布在  React
关注(0)|答案(2)|浏览(129)

我正在使用React Hook Forms,我想在处理中发送接收Checkbox值,默认设置为true我注册了组件,一切都很好,但如果我没有触摸任何东西(尽管复选框的值设置为true),我会得到undefined,但只要我手动更改复选框的值,它就会正常传输。告诉我赋值是怎么回事?

const { register, handleSubmit } = useForm();

const MyOnSubmit = (data) => {
  console.log(data);
};

const [checkemail, setcheckemail] = useState(true);

<form onSubmit={handleSubmit(MyOnSubmit)}>
  <FormControlLabel
    value={checkemail}
    control={<Checkbox defaultChecked color="primary" />}
    label="Ok"
    {...register('check')}
    onClick={(e) => {
      setcheckemail(e.target.checked);
    }}
  />

  <Button type="submit" color="primary"> 
    Sign Up
  </Button>
</form>

复选框是默认设置的,如果我不手动更改它并单击提交表单按钮,就会得到check = undefined
如果我手动设置复选框或取消选中它,那么该值将被正常传输
为什么?如何获取要传递的默认复选框值

gcmastyq

gcmastyq1#

请替换useForm和FormControlLabel来尝试此代码。它应该可以工作

const {register, handleSubmit, control  } = useForm();

  <FormControlLabel
        label={"Ok"}
        control={
          <Controller
            name="check"
            control={control}
            defaultValue={true}
            value={checkemail}
            render={({ field }) => <Checkbox {...field} defaultChecked />}
            onClick={(e) => {
              setcheckemail(e.target.checked);
            }}
          />
        }
      />

请访问https://react-hook-form.com/get-started#IntegratingControlledInputs

mcvgt66p

mcvgt66p2#

下面是在react-hook-form中使用Checkbox的正确方法

import { useForm, Controller } from "react-hook-form";
import {
  Checkbox,
  FormControlLabel,
} from "@mui/material";

const { handleSubmit, control } = useForm()
...

<Controller
  control={control}
  name={`${item.id}`}
  defaultValue={!!evaluationDimensions?.[item.id]?.selected} 
  render={({ field: { onChange, value } }) => (
    <FormControlLabel
      control={
        <Checkbox
          checked={value}
          onChange={onChange}
        />
      }
    />
  )}
/>
...

确保在使用checked={value}时使用defaultValue,以防止出现以下问题

React warning MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized

相关问题