我只想做点如下的事情:
<div class="container"> <div class="row"> <div class="col-md-4">content</div> <div class="col-md-4">content</div> <div class="col-md-4">content</div> </div> <div class="row"> <div class="col-md-4">content</div> <div class="col-md-4">content</div> <div class="col-md-4">content</div> </div> <!-- etc ... --> </div>
例如,每3个.col-md-4被包裹在一个.row中
我试过了:
rows.push(<div className="row">); for (var count = 0; count < 9; count++) { rows.push( <!-- content --> ); // Add closing and reopening divs every 3 elements if (count % 3 === 0) { rows.push(</div><div className="row">); } } rows.push(</div>); }
遗憾的是,这不起作用.
此外,3和9只是这里的例子,我想知道是否有通用的方法.
解决方法
您不应该像字符串那样连接元素,而是创建和组合反应元素.您可以先使用内容生成元素数组,然后将其缩小为组并使用容器包装:
render() { var content = [ "content 1","content 2","content 3","content 4","content 5","content 6","content 7","content 8","content 9","content 10" ]; var groupSize = 3; var rows = content.map(function(content) { // map content to html elements return <div className="col-md-4">{content}</div>; }).reduce(function(r,element,index) { // create element groups with size 3,result looks like: // [[elem1,elem2,elem3],[elem4,elem5,elem6],...] index % groupSize === 0 && r.push([]); r[r.length - 1].push(element); return r; },[]).map(function(rowContent) { // surround every group with 'row' return <div className="row">{rowContent}</div>; }); return <div className="container">{rows}</div>; }