警告:在< select>上使用'defaultValue'或'value'属性.而不是在< option>上设置'selected' [英] Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

查看:391
本文介绍了警告:在< select>上使用'defaultValue'或'value'属性.而不是在< option>上设置'selected'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SCENARIO 用户具有一个下拉菜单,并且他选择了一个选项.我想显示该下拉菜单,并将该选项设置为该用户上次选择的默认值.

SCENARIO A user has a dropdown and he selects an option. I want to display that dropdown and make that option a default value which was selected by that user last time.

我在选项上使用 selected 属性,但是React生成警告,要求我在select上使用默认值.

I am using selected attribute on option but React generates a warning asking me to use default value on select.

例如

render: function() {
    let option_id = [0, 1];
    let options = [{name: 'a'}, {name: 'b'}];
    let selectedOptionId = 0

    return (
      <select defaultValue={selectedOptionId}>
        {option_id.map(id =>
        <option key={id} value={id}>{options[id].name}</option>
        )}
      </select>
    )
  }
});

问题是我不知道 selectedOptionId ,因为所选选项可能是任何选项.我如何找到 defaultValue ?

Problem is that I don't know the selectedOptionId as the selected option could be any option. How would I find the defaultValue ?

推荐答案

React使用 value代替selected ,以确保表单组件之间的一致性.您可以使用defaultValue设置初始值.如果您要控制值,则应设置以及.如果没有,请不要设置value,而应处理onChange事件以对用户操作做出反应.

React uses value instead of selected for consistency across the form components. You can use defaultValue to set an initial value. If you're controlling the value, you should set value as well. If not, do not set value and instead handle the onChange event to react to user action.

请注意valuedefaultValue应该与选项的value相匹配.

Note that value and defaultValue should match the value of the option.

这篇关于警告:在&lt; select&gt;上使用'defaultValue'或'value'属性.而不是在&lt; option&gt;上设置'selected'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆