【问题标题】:React Hook Form validation using nested custom checkbox component使用嵌套的自定义复选框组件进行 React Hook Form 验证
【发布时间】:2021-08-09 09:51:13
【问题描述】:

我正在使用 React Hook 表单。我制作了一个自定义复选框,如下所示:

const Checkbox = ({ text, className, setCheckbox, checkbox }) => {
  const { register } = useFormContext();
  const statute = register("statute");
  return (
    <Wrapper className={className}>
      <StyledLabel>
        <div>{text}</div>
        <StyledInput
          type="checkbox"
          name="statute"
          onChange={(e) => {
            statute.onChange(e);
            setCheckbox && setCheckbox(!checkbox);
          }}
        />
        <Checkmark />
      </StyledLabel>
    </Wrapper>
  );
};

复选框(Checkbox.js)嵌套在父组件(Register.js)中:

const Register = ({ setRegisterView }) => {
  const validationSchema = Yup.object().shape({
    statute: Yup.bool().oneOf([true], "You need to accept the page statute."),
  });

  const methods = useForm({
    mode: "onSubmit",
    resolver: yupResolver(validationSchema),
  });

  const {
    register: validate,
    formState: { errors },
    handleSubmit,
  } = methods;

  return (
    <Wrapper>
      <FormProvider {...methods}>
        <Form onSubmit={handleSubmit(registerProcess)}>
          <StyledCheckbox
            text="Accept the page statute."
            setCheckbox={null}
            checkbox={null}
          />
          {errors.statute && <Error>{errors.statute.message}</Error>}
          <LoginButton type="submit">SIGN UP</LoginButton>
        </Form>
      </FormProvider>
    </Wrapper>
  );
};

export default Register;

问题是,当我选中复选框时,我在errors.statute.message 中得到一条信息:statute must be a `boolean` type, but the final value was: `"on"`.

当我改变这个时:

onChange={(e) => {
            statute.onChange(e);
            setCheckbox && setCheckbox(!checkbox);
          }}

到这里:

{...register("statute")}

然后它工作得很好,errors.statute.message 仅在复选框输入中的 checked=false 时显示正确的消息。但我需要有onChange的扩展版本。

【问题讨论】:

    标签: javascript reactjs forms react-hook-form


    【解决方案1】:

    问题是,您没有将register 调用返回的ref 链接到您的&lt;StyledInput /&gt;。所以只需传播register 的返回值——在下面的代码示例中,我还省略了name 属性,因为它包含在statute 中。 Here你可以找到register会返回的所有道具。

    <StyledInput
      type="checkbox"
      {...statute}
      onChange={e => {
        statute.onChange(e);
        setCheckbox && setCheckbox(!checkbox);
      }}
    />
    

    【讨论】:

    • 是的,就是这样!现在效果很好!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2021-11-05
    • 2021-08-25
    • 2021-04-28
    • 1970-01-01
    • 2022-10-16
    • 2023-03-11
    相关资源
    最近更新 更多