reactjs - 如何有条件地禁用输入取决于“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>
解决方案
你可以使用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>
);
推荐阅读
- ruby-on-rails - 当开发环境使用 RVM 时,如何在带有 Rbenv 的服务器上部署 Capistrano?
- excel - Excel 提取过滤器单元格
- apache-spark - CDH 6.2 Hive 无法在 Spark 和 MapReduce 上执行查询
- mysql - 用于添加列的 SQL 查询
- c# - 使用 linq、ToDictionary(...) 读取 .txt 文件,选择数组范围
- javascript - 线性渐变在 Chrome 上不响应,但在 FireFox 上响应,为什么?
- scala - Gatling exec 与会话
- python - LinAlgError:奇异矩阵,求解线性方程 python
- yii2 - SES SMTP 邮件给 openssl :EVP_CIPHER_CTX_set_key_length:invalid key length 错误
- selenium - 在 docker 中安装 Genymotion