react.js每第n个项目添加开始标记或结束标记
我在使用此逻辑时遇到麻烦,因为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">
;
下面的代码 _ _ 用另一种语言工作,但是由于我们按下了结束标记和开始标记(这是无效的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.
回答:
render() { const rows = array_chunk(this.props.columns, 4)
return (
{
rows.map((row) => (
<div className="row">
{
row.map((col) => (
<div className="col">{ col }</div>
))
}
</div>
))
}
)
}
一个array_chunk示例(我建议您使用lodash)
module.exports = function chunks(arr, size) { if (!Array.isArray(arr)) {
throw new TypeError('Input should be Array');
}
if (typeof size !== 'number') {
throw new TypeError('Size should be a Number');
}
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, size + i));
}
return result;
};
以上是 react.js每第n个项目添加开始标记或结束标记 的全部内容, 来源链接: utcz.com/qa/400440.html