[英]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.