如何有条件地禁用输入取决于“React-hook-form”中的另一个输入值?
How to conditional disable input depend on another input value in "React-hook-form'?
我想根据另一个输入值有条件地禁用输入。常见的用例是我们有一个复选框,我们需要 disable/enable 另一个相同表单的输入。我怎样才能用 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>
您可以使用 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>
);
我想根据另一个输入值有条件地禁用输入。常见的用例是我们有一个复选框,我们需要 disable/enable 另一个相同表单的输入。我怎样才能用 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>
您可以使用 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>
);