reactjs - 渲染数组将内容与样式分开

reactjs - render array separating contents from styles

我正在考虑将数据数组重构为每行 4 列。

当前反应沙箱 https://rtcex.csb.app/

所以假设内容是这样的

let rowContents = [
    {"id": "col1Id", "type": "label", "contents": "col 1"},
    {"id": "col2Id", "type": "value", "contents": "col 2"},
    {"id": "col3Id", "type": "label", "contents": "col 3"},
    {"id": "col4Id", "type": "value", "contents": "col 4"},
    {"id": "col5Id", "type": "label", "contents": "col 5"},
    {"id": "col6Id", "type": "value", "contents": "col 6"}
];

我目前有一张地图呈现这样的数据

{
 rowContents.map(function(item, i){
  return (
    <Col key={i} id={item.id} className={"col-md-3 " + item.type}>{item.contents}</Col>
  );
 })
}

-- 但这只会呈现所有 col 标记--我想向呈现器添加一个 header/footer 方面,以便它在每第 4 个元素处添加一个行包装器。

例如预期输出

<Row>
    <Col id="col1Id" className="col-md-3 label">col1</Col>
    <Col id="col2Id" className="col-md-3 value">col2</Col>
    <Col id="col3Id" className="col-md-3 label">col3</Col>
    <Col id="col4Id" className="col-md-3 value">col4</Col>
<Row>
<Row>
    <Col id="col5Id" className="col-md-3 label">col5</Col>
    <Col id="col6Id" className="col-md-3 value">col6</Col>
<Row>

一种简单的方法是使用辅助函数来拆分所有内容,然后对其进行分组。

注意:该函数可以与其他分割数一起使用,因此您可以更改 <Rows/>

<Cols/> 的数量
function spliceArrayInGroups(list, howMany) {
  var result = []
  input = list.slice(0)
  while (input[0]) {
    result.push(input.splice(0, howMany))
  }
  return result;
}

const separatedInGroups = spliceArrayInGroups(rowContents, 4);

const result = separatedInGroups.map(function(row, ri) {
  // here you iterate over your grouped items and form your cols.
  const cols = item.map((item, ci) => <Col key={ri+'-'+ci} id={item.id} className={"col-md-3 " + item.type}>{item.contents}</Col>)

  // then you wrap them into a row.
  return <Row key={${ri}}>${cols}<Row>
})

你可以使用一个帮助函数(使用Array#reduce):

const r = [{ foo: 1 }, { foo: 2 }, { foo: 3 }, { foo: 4 }, { foo: 5 }, { foo: 6 }];
const getData = (r, splitBy) => r.reduce((s, a) => (s[0].push(a), s[0].length === splitBy ? (s.push(s[0]), s[0] = []) : s, s), [[]]).filter((a) => a.length).reverse();

console.log(getData(r, 4));

然后在内部渲染:

{
  getData(rowContents).map((item, i) => {
    return (
      <Row>
         {item.map((item) => 
           <Col key={i} id={item.id} className={"col-md-3 " + item.type}>
              {item.contents}
           </Col>
         )}
      </Row>
    );
  })
}

但是可能会有一些更易读的解决方案,只是想对其进行一些调整。