首页 > 解决方案 > 反应表单中带有单选按钮的条件字段是否有效?

问题描述

我正在创建一个带有“职业”字段作为单选按钮的表单。职业有两种选择——自雇和服务。根据用户对职业的选择,我显示了表单的不同字段。我正在使用 if-else 进行此条件渲染。代码适用于 if 部分,但不适用于 else 部分。我附上我的代码以供参考。

                  <div className="row">
                    <div className="col-md-3">
                      <input 
                        type= "radio"
                        id= "fatherService"
                        name= "fatherOccupation"
                        value = "service"
                        checked={fatherOccupation === "service"}
                        onChange={handleFatherOccupation}
                      />
                      <label htmlFor="fatherService">Service</label>
                    </div>
                    <div className="col-md-6">
                      <input 
                        type= "radio"
                        id= "fatherSelfEmployed"
                        name= "fatherOccupation"
                        value = "selfEmployed"
                        checked={fatherOccupation === "selfEmployed"}
                        onChange={handleFatherOccupation}
                      />
                      <label htmlFor="fatherSelfEmployed">Self Employed</label>
                    </div>  
                  </div>
                </div>
              </div>
              {fatherOccupation === "service" ? (
                <div className="row">
                  <div className="col-md-6">
                    <label>Company Name:</label>
                    <input 
                      type="text"
                      className="form-control p-2"
                      id="fatherCompanyName"
                      name="fatherCompanyName"
                      {...register("fatherCompanyName", {
                        required:"Please enter father's company name",  
                      })}
                    />
                  </div>
                </div>  
              ) : (
                <div className="row">
                  <div className="col-md-6">
                    <label>Type of Business:</label>
                    <input 
                      type="text"
                      className="form-control p-2"
                      id="fatherTypeOfBusiness"
                      name="fatherTypeOfBusiness"
                      {...register("fatherTypeOfBusiness", {
                        required:"Please enter father's type of business",  
                      })}
                    />
                  </div>
                </div>
              )}

标签: javascriptreactjsreact-hooksreact-hook-form

解决方案


推荐阅读