React - 显示可变行数

React - display variable number of rows

我有一个 table,用户可以向其中添加和删除行。行的 HTML 由 this.displayRow() 创建,行数存储在 this.state.rowNr 中。我想显示 this.state.rowNr 行,所以像这样:

displayTableBody: function() {
    return(<div>
        {
            for(i = 0 ; i < this.state.rowNr ; i++) {
                this.displayRow();
            }
        }
    </div>);
}

然而,这不是有效的 JSX 语法。

您可以将包含行的数组分配给变量并将其呈现在您的 div:

displayTableBody: function() {
    var rows = Array.apply(null, Array(this.state.rowNr)).map(function(el) { return this.displayRow(); })
    return (<div> { rows } </div>);
}

或者,使用 lodash(JavaScript 实用程序库):

displayTableBody: function() {
    var rows = _.times(this.state.rowNr).map(this.displayRow);
    return (<div> { rows } </div>);
}

代码 Array.apply(null, Array(this.state.rowNr)) 创建了一个长度为 this.state.rowNr 且具有未定义值的数组。

然后将每个 undefined 值转换(或 映射 )为函数 this.displayRow() 的结果。我假设这个函数 returns 一个包含一行的元素。

还要检查此函数的结果 displayTableBody 是否用于 render 方法。

React 只能渲染对象或数组,不能渲染 javascript 表达式。

将 for 循环移出 return 并在那里进行计算。

displayTableBody: function() {
   var rows = [];
   for(i = 0 ; i < this.state.rowNr ; i++) {
       rows.push(this.displayRow());
   }
   return <div>{rows}</div>;
}

你可以这样做:

displayTableBody: function() {
    var rows = [];

    for (var i = 0; i < this.state.rowNr; i++) {
      rows[i] = this.displayRow();
    }

    return(<div>{rows}</div>);
}