![](/img/trans.png)
[英]Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>
[英]Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>
我写了以下代码,但出现错误:
index.js: 1 警告:在<select>
上使用defaultValue
或value
道具,而不是在<option>
上设置selected
。
我面对
<div className='form-group'>
<label>Parent category</label>
<select
name='category'
className='form-control'
onChange={(e) => setParent(e.target.value)}
defaultValue={parent}
>
<option>Please select</option>
{categories.length > 0 &&
categories.map((c) => (
<option selected={c._id} key={c._id} value={c._id === parent}>
{c.name}
</option>
))}
</select>
</div>
您不应该将selected
的属性放在option
中。 而是使用select
的value
属性。
并且始终遵循此规则,即组件可以受控或不受控。 如果您在 onChange 中使用 setter,则不要使用defaultValue
。 使用value
属性并将其设置为 state 变量。
您的代码应如下所示(或在此处找到有效的代码框链接):
<div className="form-group">
<label>Parent category</label>
<select
name="category"
className="form-control"
onChange={(e) => setParent(e.target.value)}
value={parent}
>
<option>Please select</option>
{categories.length > 0 &&
categories.map((c) => (
<option key={c._id} value={c._id}>
{c.name}
</option>
))
}
</select>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.