You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用React Hook Form设置Checkbox默认选中后值无法更新的问题

解决React Hook Form中Checkbox默认选中后无法更新的问题

问题出在你手动添加的checked={true}上——这个硬编码的属性会覆盖React Hook Form通过{...field}传递的受控状态,导致Checkbox被固定为选中状态,完全忽略表单内部的状态更新。

你最初的代码其实已经正确实现了默认选中的需求:通过Controller的defaultValue={true},已经把graph_outline字段的初始值设为true,{...field}会自动把这个状态同步到Checkbox上,同时也会绑定 onChange 事件来更新表单状态。

修正后的代码只需要去掉手动添加的checked={true}即可:

<Controller
  defaultValue={true}
  name="graph_outline"
  control={methods.control}
  render={({ field }) => (
    <>
      <br />
      <InputLabel>Graph Outline</InputLabel>
      <FormControlLabel control={<Checkbox {...field} />} label="Graph Outline" />
    </>
  )}
/>

如果后续需要动态修改这个Checkbox的状态,不要直接操作checked属性,而是用React Hook Form提供的setValue方法:

// 示例:在事件中切换状态
methods.setValue('graph_outline', !methods.getValues('graph_outline'))

内容的提问来源于stack exchange,提问作者vidur punj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:02:39