React:如何通过下拉框特定选项启用禁用的声明人标签页按钮
实现方法
因为你在用react-hook-form,直接用它的watch API监听下拉框变化是最贴合的方案,无需额外使用useState,具体步骤如下:
- 引入并使用
watch函数
从react-hook-form的useForm中解构出watch,实时监听Declaranttype字段的取值:
const { register, handleSubmit, watch } = useForm(); // 监听Declaranttype字段 const declarantType = watch("Declaranttype");
- 判断标签页按钮的禁用状态
定义逻辑:当选中值为10(Father)或1(Mother)时,禁用Declarant's data按钮,否则启用:
const isDeclarantTabDisabled = ["10", "1"].includes(declarantType);
- 给标签页按钮绑定
disabled属性
修改Declarant's data对应的按钮,添加disabled属性:
<button className="nav-link" data-bs-target="#abadeclarante" data-bs-toggle="tab" type="button" disabled={isDeclarantTabDisabled} > Declarant's data </button>
完整修改后的核心代码片段
import { useForm } from "react-hook-form"; function YourFormComponent() { const { register, handleSubmit, watch } = useForm(); const declarantType = watch("Declaranttype"); const isDeclarantTabDisabled = ["10", "1"].includes(declarantType); const handleSubmitForm = (data) => { // 你的表单提交逻辑 console.log(data); }; return ( <h2 className="bg-primary text-light rounded-top mb-0 pb-0 pessoaheader container">Registration Form</h2> <form className="form-inline container border border-dark rounded-bottom formelement" onSubmit={handleSubmit(handleSubmitForm)}> <br /> <nav className="nav nav-tabs"> <button className="nav-link active" data-bs-target="#abafilho" data-bs-toggle="tab" type="button"> Child's Data</button> <button className="nav-link" data-bs-target="#abamae" data-bs-toggle="tab" type="button"> Mother's data</button> <button className="nav-link" data-bs-target="#abapai" data-bs-toggle="tab" type="button"> Father's Data</button> <button className="nav-link" data-bs-target="#abadeclarante" data-bs-toggle="tab" type="button" disabled={isDeclarantTabDisabled} > Declarant's data </button> </nav> <div className="tab-content"> <div className="tab-pane active show fade" id="abafilho"> <div className="form-filho"> <div className="row pt-3"> <div className="col-lg-2 col-md-3 mb-2"> <label className="formlabels" htmlFor="Declaranttype">Declarant</label> <select className="form-select form-control selecttype" id="Declaranttype" {...register("Declaranttype")}> <Declaranttype /> </select> </div> </div> </div> </div> </div> <div className="tab-pane show fade" id="abapai"></div> <div className="tab-pane show fade" id="abadeclarante"></div> <button className="btn btn-primary btn-lg fw-semibold formbutton display-4 m-1" type="submit">Submit</button> </form> ); }
说明
watch函数会自动追踪指定字段的变化,当下拉框选项改变时,declarantType会实时更新,进而触发按钮禁用状态的切换,完全贴合react-hook-form的数据流。- 这种方式无需额外维护状态,代码更简洁高效。
内容的提问来源于stack exchange,提问作者Caio Urtiga
相关产品推荐
相关产品推荐

