React无法从选择多个表单中进行选择

时间:2016-07-11 03:45:48

标签: javascript jquery forms reactjs coffeescript

所以我在React.js中创建了一个select multiple表单,但每次生成选项时,我都无法选择选项。如果我点击某个选项,它会立即突出显示而不会被选中。

React.DOM.div({
  className: 'form-group'
}, React.DOM.select({
     multiple: true,
     name: 'team_players',
     value: this.state.team_players,
     onChange: this.handleArrayChange
}, React.DOM.option({
     value: '',
     disabled: true
}, 'Select Players'), (function() {
    var i, len, ref, results;
    ref = this.state.players;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
       player = ref[i];
       results.push(React.DOM.option({
       key: player.id,
       value: player.detail.inputs["NAME"]
    }, player.detail.inputs["NAME"]));
 }
 return results;
}).call(this)));

*请注意,这是我的coffeescript版本通过js2.coffee生成的js版本,如下所示:*

React.DOM.div
className: 'form-group'
React.DOM.select
  multiple: true
  name: 'team_players'
  value: @state.team_players
  onChange: @handleArrayChange
  React.DOM.option
    value: ''
    disabled: true
    'Select Players'
    for player in @state.players
      React.DOM.option
      key: player.id
      value: player.detail.inputs["NAME"]
      player.detail.inputs["NAME"]

我的handleArrayChange函数如下:

({
handleArrayChange: function(e) {
  var i, len, name, obj, option, options, team_array;
  options = e.target.options;
  name = e.target.name;
  team_array = [];
  for (i = 0, len = options.length; i < len; i++) {
    option = options[i];
    team_array.push(option);
  }
  return this.setState((
    obj = {},
    obj["" + name] = team_array,
    obj
  ));
}
});

并以其coffescript形式:

handleArraychange: (e) ->
  options = e.target.options
  name = e.target.name
  team_array = []
  for option in options 
    team_array.push option
  @setState "#{name}": team_array

为什么这种形式无法正确处理我的输入?

1 个答案:

答案 0 :(得分:2)

您将team_array状态设置为选项HTML元素的数组,而不是字符串数组。试试这个:

handleArraychange: (e) ->
  options = e.target.options
  name = e.target.name
  team_array = []
  for option in options 
    team_array.push option.value
  @setState "#{name}": team_array