【问题标题】:react.js every nth item add opening tag or closing tagreact.js每第n个项目添加开始标签或结束标签
【发布时间】:2016-07-19 00:47:53
【问题描述】:

我在这个逻辑上遇到了问题,因为 react/jsx 不允许将非结束标签添加到数组/子组件中。例如,使用引导 css 我想为 4 列添加一行。

所以逻辑如下:

添加一个开始行,例如:<div className="row">,然后在该行内循环,每个循环附加一个列,例如:<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.

【问题讨论】:

  • > 适用于任何其他语言 JSX 不是字符串连接语言。它将被转译为实际的 JS 代码,因此您的代码将无法工作
  • 我知道,那么用 React / JSX 处理这个逻辑的正确方法是什么?
  • 你能用你想要生成的 HTML 标记更新你的问题吗?
  • 更新了@NguyễnĐăngKhoa
  • 行应该是带有列组件的组件。

标签: javascript html twitter-bootstrap reactjs jsx


【解决方案1】:
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;
};

【讨论】:

  • 如何处理 9 列?如果大小为 2(2 个 4 块),您将丢失第 9 项...
  • 它将创建具有 4 列的第一行和具有 3 列的第二行。这就是 array_chunk 的工作原理。
  • @AntonB 映射两次是 O(2n) == O(n);为每个 n 映射一个完整的集合将是 O(n^2)
  • 也许吧。但根据我使用 React.js 的经验。这是解决这个问题的唯一方法。
  • @Mathletics 好点,我站得更正-感谢您的回答:)
【解决方案2】:

我实际上只是使用了数组,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>
    )
}

【讨论】:

    猜你喜欢
    • 2012-05-21
    • 1970-01-01
    • 2012-09-20
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    相关资源
    最近更新 更多