react.js 每第 n 个项目添加开始标签或结束标签

react.js every nth item add opening tag or closing tag

由于 react/jsx 不允许将非结束标记添加到 array/child 组件,因此我在处理此逻辑时遇到了问题。例如 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 很好地处理了渲染。

render() {
    let rows = [],
        cols = []
    let index = 0
    const totalCols = 20;

    for (index; index < totalCols; index++) {
        cols.push(<div class="col" key={index}/>)
        if ((index + 1) % 4 == 0) {
            rows.push(
                <div class="row" key={index}>
                    {cols}
                </div>
            )
            cols = []
        }
    }
    return (
        <div class="container">
            {rows}
        </div>
    )
}