复选框组件不工作。 (MATERIAL UI, REACT-HOOK-FORM

Checkbox component not working. (MATERIAL UI, REACT-HOOK-FORM

我正在使用 material 复选框,但它不会 return 是真还是假。这是我的代码:

 <FormControlLabel
      control={
        <Checkbox defaultValue={data.hasPhone} defaultChecked={data.hasPhone} color="primary" {...register("hasPhone")}/>            
      }
      label="Do you have a phone"
    />

{hasPhone && (
              <Input
                {...register("phoneNumber")}
                id="phoneNumber"
                type="tel"
                label="Cellulare"
                name="phoneNumber"
              />
            )}

当复选框为真时,我们有条件“hasPhone”打开另一个输入字段。 如果我像这样使用我的复选框:

<input type="checkbox" placeholder="Developer" {...register("hasPhone")} />

在上述情况下,条件正常工作。

你能帮帮我吗?谢谢

它之所以适用于您的“hasPhone”<input />,是因为它是原生表单元素,与 Material UI <Checkbox /> 组件相比,这是一个外部控制输入。

因此,对于原生表单元素,您可以使用 register,但对于外部控制组件,您必须使用 RHF 的 <Controller /> 组件。在文档中查看此 section 以获取更多信息。