首页 > 解决方案 > 如何有条件地禁用输入取决于“React-hook-form”中的另一个输入值?

问题描述

我想根据另一个输入值有条件地禁用输入。常见的用例是我们有一个复选框,我们需要以相同的形式禁用/启用另一个输入。我怎样才能用 react-hook-form 实现它?我想禁用,而不是提交时的验证。

目前,我正在使用FormControlLabel(material-ui) 和 react-hook-form 。任何帮助将不胜感激。

更新!这是我的想法的一个小演示代码

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

const { control } = useForm({/* some options */});

// Below is render function

<form onSubmit={handleSubmit(onSubmit)}>
  <Controller
  name="checkbox"
  control={control}
  render={({ field: { onChange, value }}) => {
    return (
      <FormControlLabel
        control={
          <Checkbox
            checked={value}
            onChange={e => {
              onChange(e.target.checked);
            }}
          />
        }
        label="Enable text input?"
        labelPlacement="end"
      />
    );
  }}
/>
<Controller
  name="text-input"
  control={control}
  render={({ field: { onChange, value } }) => {
    return (
      <TextField
        value={value}
        onChange={onChange}
        disabled={/* WHAT TO DO HERE???? */}
      />
    );
  }}
/>;
</form>

标签: reactjsmaterial-uireact-hook-form

解决方案


你可以使用watch

const {register, watch} = useForm();

return ( 
<div>
  <input type="checkbox" ref={register} name="input-a" />
  <input ref={register} name="input-b" disabled={!watch("input-a")} />
</div>
);

推荐阅读