ReactJs - 列表组件

时间:2016-04-20 22:27:58

标签: javascript reactjs

您好我想在列表组件中嵌套列表组件。第一个列表是选项组列表,其每个项目都有一个选项列表。我认为问题来自嵌套的IndicatorRow。我无法找到相同的例子。

var IndicatorRow = React.createClass({
 render: function() {

  var indicators = [];

  for (var key in this.props.indicatorsOfGroup) {
      indicators.push( <option value={key} > {this.props.indicatorsOfGroup[key]}</option> );
  }

  return {indicators} ;
 }
});

var IndicatorGroup = React.createClass({
render : function(){

  var indicatorsGroup = [];
  for (var key in this.props.indicatorsGroups) {

      var indicatorsOfGroup = this.props.indicatorsGroups[key].indicators;

      indicatorsGroup.push( 
         <optgroup label={key}> 
             <IndicatorRow indicatorsOfGroup={indicatorsOfGroup}/>
         </optgroup> );

  }

    return ( <select> 
                {indicatorsGroup} 
            </select> );
}
});

ReactDOM.render(
    <form>
        <fieldset className="form-group">
            <IndicatorGroup indicatorsGroups={indicatorsSelected}/>
        </fieldset>
    </form>
 ,
 document.getElementById('indicators')
);

我的数据结构如下

var indicatorsSelected = {
"Economy & Growth": {
    "indicators": {
        "id1": "Indicator 1",
        "id2": "Indicator 2"
    }
},
"Energy & Mining": {
    "indicators": {
        "id1": "Indicator 1",
        "id1": "Indicator 2"
    }
},
"Environment": {
    "indicators": {
        "id1": "Indicator 1",
        "id2": "Indicator 2"
    }
},
{...}
};

我将不胜感激任何帮助

1 个答案:

答案 0 :(得分:1)

2个问题:

  1. 您无法从render
  2. 返回数组
  3. 您的数组子项均需要key属性
  4. 类似的东西:

    var IndicatorRow = React.createClass({
      render: function() {
        var indicators = [];
    
        for (var key in this.props.indicatorsOfGroup) {
          indicators.push( <option key={key} value={key} > {this.props.indicatorsOfGroup[key]}</option> );
        }
    
        return (<optgroup  label={key}>
          {indicators}
        </optgroup>);
      }
    });
    
    var IndicatorGroup = React.createClass({
      render: function(){
        var indicatorsGroup = [];
        for (var key in this.props.indicatorsGroups) {
          var indicatorsOfGroup = this.props.indicatorsGroups[key].indicators;
    
          indicatorsGroup.push( 
            <IndicatorRow key={key} indicatorsOfGroup={indicatorsOfGroup}/>
          );
    
        }
        return (<form>
          <fieldset className="form-group">
            <select> 
              {indicatorsGroup} 
            </select>             
          </fieldset>
        </form>);
      }
    
    });
    
    ReactDOM.render(
    <IndicatorGroup indicatorsGroups={indicatorsSelected}/>,
     document.getElementById('indicators')
    );