在React js中为Select Field提供默认值

时间:2018-02-20 09:41:54

标签: javascript reactjs

我有以下选择字段:

    <SelectField
      id={quesId}
      required
      menuItems={opts}
      style={style.selectionStyle}
      className="md-cell"
      defaultValue = {value}
    />

这里,opts是一个对象数组:

    opts = [{id: "1", value: "1", label: "DL"},
            {id: "2", value: "2", label: "UP"},
            {id: "3", value: "3", label: "PB"},
            {id: "4", value: "4", label: "MH"},
            {id: "5", value: "5", label: "WB"},
            {id: "6", value: "6", label: "KN"},
            {id: "7", value: "7", label: "GJ"},
            {id: "8", value: "8", label: "RJ"},
            {id: "9", value: "9", label: "BR"},
            {id: "10", value: "10", label: "TN"},
            {id: "11", value: "11", label: "AP"},
            {id: "12", value: "12", label: "TN"}]

我想要做的是将我的选择字段的默认值设置为“AP”,我传递的值是

    value = {id: "11", value: "11", label: "AP"}

此处的问题是未设置选择字段的默认值。没有做什么。提前致谢

2 个答案:

答案 0 :(得分:0)

这是你需要实现的吗?

demo

从以下状态分配选择值:

class App extends Component {
  constructor(props) {
    super(props);
    this.handleLangSelect = this.handleLangSelect.bind(this);
    this.state =  {
      "lang_selected": "English"
    };
  }

  handleLangSelect(event) {
      this.setState({lang_selected:event.target.value});
  }

  render() {
    return (
      <div>
        <select className="form-control" id="langSelect" value={this.state.lang_selected} onChange={this.handleLangSelect}>
            <option>Others</option>
            <option>French</option>
            <option>English</option>
        </select>
      </div>
    );
  }
}

希望有所帮助

答案 1 :(得分:0)

根据Docs所述,该值应与菜单项itemValue中的一个匹配,或者为空字符串。

所以你可以把它设置为:

<SelectField
  id={quesId}
  required
  menuItems={opts}
  style={style.selectionStyle}
  className="md-cell"
  defaultValue={opts[10].value}
/>