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

如何在React-hook-form中根据另一输入值动态禁用指定输入组件

实现方案

你可以通过react-hook-form提供的watch方法监听复选框字段的实时值,直接控制输入框的禁用状态即可,具体实现如下:

首先修改useForm的解构逻辑,新增watch方法和默认值配置,完整代码示例:

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

// 从useForm中解构出需要的方法,添加watch用于监听字段变化
const { control, handleSubmit, watch } = useForm({
  // 建议给复选框设置初始默认值,避免初始状态为undefined导致异常
  defaultValues: {
    checkbox: false,
    "text-input": ""
  }
});

// 实时监听checkbox字段的取值
const isTextInputEnabled = watch("checkbox");

// 渲染函数部分
<form onSubmit={handleSubmit(onSubmit)}>
  <Controller
    name="checkbox"
    control={control}
    render={({ field: { onChange, value }}) => (
      <FormControlLabel
        control={
          <Checkbox
            checked={value}
            onChange={e => onChange(e.target.checked)}
          />
        }
        label="启用文本输入框?"
        labelPlacement="end"
      />
    )}
  />
  <Controller
    name="text-input"
    control={control}
    render={({ field: { onChange, value } }) => (
      <TextField
        value={value}
        onChange={onChange}
        // 直接取监听结果的反值作为disabled属性
        disabled={!isTextInputEnabled}
      />
    )}
  />
</form>

可选优化

如果需要在禁用输入框的同时清空已填写的内容,可以在复选框的change事件中补充逻辑,需要先从useForm中额外解构出setValue方法:

<Checkbox
  checked={value}
  onChange={e => {
    const checked = e.target.checked;
    onChange(checked);
    // 取消勾选时清空文本输入框内容
    if (!checked) {
      setValue("text-input", "");
    }
  }}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:57:02