首页 > 解决方案 > 带有 react-hook-form 的 material-ui 复选框

问题描述

我无法使用 react-hook-formreset方法以编程方式设置 material-ui 复选框的值

这里有一个我的代码示例,您可以注意到,它TextField可以正常工作,CheckBox但不能!

https://codesandbox.io/s/cocky-shamir-8lqph?file=/src/App.js

标签: material-uireact-hook-form

解决方案


根据控制器示例文档,您可以使用Controllerfromreact-hook-form正确更改材质 UI 复选框的值。沙盒

第一个复选框(没有标签)如下:

<Controller
          name="checkwithoutlabel"
          control={control}
          defaultValue={false}
          rules={{ required: true }}
          render={(props) => (
            <Checkbox
              onChange={(e) => props.onChange(e.target.checked)}
              checked={props.value}
            /> 
          )}
/>

FormControlLabel组件应该写成这样:

<FormControlLabel
          control={
            <Controller
              name={"checkwithlabel"}
              control={control}
              defaultValue={false}
              render={(props) => (
                <Checkbox
                  {...props}
                  checked={props.value}
                  onChange={(e) => props.onChange(e.target.checked)}
                />
              )}
            />
          }
          label={"Checkbox with label"}
        />

推荐阅读