我在使用此逻辑时遇到麻烦,因为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">

下面的代码将用另一种语言工作,但是在 react 中这是不可行的,因为我们按下了结束标记和开始标记(这是无效的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;
};

关于javascript - react.js每第n个项目添加开始标记或结束标记,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36318601/

10-11 23:53
查看更多