簡體   English   中英

ReactJs,如何將輸入類型從“文本”動態更改為“選擇”?

[英]In ReactJs, How to dynamically change the Input type from "text" to "select"?

我有以下代碼

                 <Controller
                  control={control}
                  name='part'
                  render={({ field }) => (
                    <Input
                      type={(type === "fixed") ? "select" : "text"}
                      name="part"
                      className={errors.part && "is-invalid"}
                      value={field.value || ""}
                      onChange={(value) => field.onChange(value)}
                    >
                      //this code is causing error
                      {(type === "fixed") &&
                        partnOptions.map((opt) =>
                          <option value={opt.code} key={opt.code}>{opt.code}</option>
                        )
                      }
                    </Input>
                  )}
                />

我得到一個錯誤input is a void element tag and must neither have children nor use dangerouslySetInnerHTML這是可以理解的,因為我猜 type text should not have any children 如果我刪除它工作正常的map部分, Input字段將根據type值從text更改為select 那么,當Input type更改為select時,如何包含該option

事實上<Input>是一個空元素。 另外,您不應該在其中添加任何東西。 沒有類型 == "select" 的輸入。 輸入類型文檔

我強烈建議您將條件渲染切換為渲染<input type="text" /><select> elements Select with option documentation

我忘了提到我正在使用reactstrap ,所以type='select'是有效的。 我設法通過添加來實現這一點: undefined

                      {(type === "fixed") ?
                        partOptions.map((opt) =>
                          <option value={opt.code} key={opt.code}>{opt.code}</option>
                        ) : undefined
                      }

這不是執行此操作的好方法。 它不是可讀的代碼,老實說我不確定它會如何呈現或混合。在我看來就像一個等待發生的錯誤。 這是條件渲染的用例。

const myInput = type === "fixed"? <Input type="select">: <Input type="text">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM