【问题标题】:React Form Select Option with Two Hard-Coded Options (and the rest mapped)使用两个硬编码选项(其余映射)的反应表单选择选项
【发布时间】:2023-03-26 18:34:01
【问题描述】:

我对前端开发(尤其是 React)比较陌生。我通常更像是一名后端开发人员,但我团队中的其他开发人员最近离开了公司,让我一个人去尝试更好地了解我们平台的整个堆栈,这是用 React 编写的。

我们有一个带有选择控件的表单。在其当前状态下,控件具有显式的默认选项(即选择讲师),其余选项从数据库表映射。默认选项已禁用,无法选择作为选项。默认显示确实存在(这是这个故事的特定 Ux 要求)。我的任务是添加一个附加选项(即不适用),允许填写表格的人选择该选项,这样他们就不必明确选择用户名。这是我为该表单控件实现的:

<Form.Group controlId="instructor">
   <Form.Label>{t("Primary Instructor")} - <em>{t("Optional")}</em></Form.Label>
   <Form.Control
      as="select"
      custom
      required
      disabled={!inputClass.CourseId}
      value={inputClass.InstructorId || ""}
      onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
         setInputClass({
            ...inputClass,
            InstructorId: e.target.value ? parseInt(e.target.value) : null
         })
      }
   >
      <option disabled key="empty" value="">
         {t("Select an instructor")}
      </option>
      <option key="empty" value="0">
         {t("Not Applicable")}
      </option>
      {instructors.map((instructor) => {
         if (selectedCourse) {
            if (selectedCourse.OnlineOnly || isCertifiedInstructor(instructor)) {
               return (
                  <option key={instructor.UserId} value={instructor.UserId}>
                     {instructor.FirstName} {instructor.LastName}
                  </option>
               );
             }
          }
       })}
    </Form.Control>

正如您在 onChange 事件中看到的,它正在评估所选值,如果它是 false,则返回 null。如果选定的值有一个选项,它会将其解析为 int 并将表单模型的状态设置为 InstructorId 的该值。理想情况下,我希望 Select an Instructor 不可选择,并且在选择时让 Not Applicable 将 NULL 传递回数据库。但是,Select an Instructor 和 Not Applicable 不能具有相同的值。我试图将不适用的值设置为 0,但显然,onChange 事件仍将“0”评估为错误,因此它返回 null,并且下拉列表选项恢复为“选择讲师”。我不知道我可以将 Not Applicable 选项设置为哪些其他值,这将使我能够完成我需要做的事情。我也尝试在 onChange 事件中使用它:

onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
   setInputClass({
      ...inputClass,
      InstructorId: e.target.value || e.target.value == "0" ? parseInt(e.target.value) : null
   })
}

但它似乎仍然返回 null,因为下拉列表仍在恢复为“选择讲师”选项。

我想我在这里最大的问题是,无论我为“不适用”选项设置什么值,当我选择它时,它都会不断恢复为“选择讲师”选项。 (在客户端,而不是在我提交时)

我意识到这必须归功于我在表单控件上设置的 value 属性

value={inputClass.InstructorId || ""}

所以我假设不适用于选择wtih一个值为“0”的值,它将其评估为valsty和默认值为“选项。

有没有人对如何规避这个默认值有任何其他想法?

【问题讨论】:

    标签: html reactjs


    【解决方案1】:

    我也喜欢后端,有时不得不使用 React,我知道你的痛苦。

    JavaScript 的类型强制将null0 评估为false。所以inputClass.InstructorId || "" 在这两种情况下都会给你""。我被这件事抓住的次数比我想承认的要多。

    nullish coalescing operator 可能会给您带来更好的运气。当inputClass.InstructorIdnull 时,inputClass.InstructorId ?? "" 将评估为"",但当它为0不是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2015-08-04
      相关资源
      最近更新 更多