问题描述
由于react / jsx不允许将非结束标记添加到数组/子组件,因此我在此逻辑中遇到了问题。例如,用bootstrap css,我想为每列添加一行 4列。
所以逻辑如下:
I'm having trouble with this logic since react/jsx does not allow for non closing tags to be added to an array/child component. For example with bootstrap css I want to add a row for every 4 columns.
添加一个开始行例如:< div className =row>
,然后在此行内循环,每个循环附加一个当循环达到4时检查< div className =列> {this.data}< / div>
if(i %4 == 0)并添加结束< / div>
标记,同时添加新的行标记< div className =row>
;
So the logic is as follows:
另一种语言,但在作出反应这是不可行的,因为我们推一个结束标签和一个开始标签(这是无效的jsx):
Add a opening row ex: <div className="row">
, then loop inside this row and every loop append a column ex: <div className="column>{this.data}</div>
when the loop reaches 4 check with if(i % 4 == 0)
and add a closing </div>
tag while adding new row tag <div className="row">
;
The code below would work in another language but in react this is not doable since we push a closing tag and a opening tag (which is invalid jsx):
)
}
预期输出为:
The expected output would be:
<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>
//上面的内容会重复出现,并且每隔4列。
推荐答案
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)
An example array_chunk (I recommend that you use 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个项目添加开始标记或结束标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!