繁体   English   中英

使用 `defaultValue` 或 `value` 道具<select>而不是设置`selected`<option>

[英]Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>

我写了以下代码,但出现错误:

index.js: 1 警告:在<select>上使用defaultValuevalue道具,而不是在<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中。 而是使用selectvalue属性。

并且始终遵循此规则,即组件可以受控或不受控。 如果您在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM