我在这个逻辑上遇到了问题,因为 react/jsx 不允许将非结束标记添加到数组/子组件中。例如,对于 bootstrap css,我想为每4 列添加一行。
所以逻辑如下:
添加一个开始行 ex: <div className="row">
,然后在该行内循环,每个循环附加一列 ex:<div className="column>{this.data}</div>
当循环达到 4 时,检查if(i % 4 == 0)
并添加结束</div>
标记,同时添加新行标记<div className="row">
;
下面的代码可以用另一种语言工作,但在 React 中这是不可行的,因为我们推送了一个结束标签和一个开始标签(这是无效的 jsx):
generateColumns(columns) {
let newColumns = [];
columns.forEach(function(column, idx) {
newColumns.push( <div className="column"> some data </div> );
if (idx % 4 == 0) {
// Here we end the row and start a new row, works in any other language.
newColumns.push( </div> <div className="row"> );
}
});
// This array now has the proper tags for opening a row every 4th item and closing it.
return newColumns;
},
render() {
return (
<div className="row">
{this.generateColumns(this.props.columns)}
</div>
)
}
预期的输出将是:
<div class="row">
<div class="column">
Some data
</div>
<div class="column">
Some more data
</div>
<div class="column">
Other data
</div>
<div class="column">
Something else
</div>
</div>
<div class="row">
<div class="column">
Some data
</div>
<div class="column">
Some more data
</div>
<div class="column">
Other data
</div>
<div class="column">
Something else
</div>
</div>
//the above would be repeated and new rows would appear every 4 columns.