按垂直顺序排列元素

时间:2018-05-16 18:57:40

标签: reactjs

找到了一些答案,但都是在多维数组上实现的。

我有一个场景,我需要以垂直顺序渲染数组元素。

预期行为:

  
      
  1. 获取给定数组的长度并将数组拆分为四列。
  2.   
  3. 每列最多应包含6个项目。
  4.   

预期产出:

1 7 13 19
2 8 14 20
3 9 15 21
4 10 16 22
5 11 17 23
6 12 18 24

样本数组:

{
  "items": [
    {
      "val": "1"
    },
    {
      "val": "2"
    },
    {
      "val": "3"
    },
    {
      "val": "4"
    },
    {
      "val": "5"
    },
    {
      "val": "6"
    },
    {
      "val": "7"
    },
    {
      "val": "8"
    },
    {
      "val": "9"
    }
  ]
}

这是我尝试过的,无法达到预期的输出。

createList(list, index) {
    const max = Math.max.apply(null, list.items.map((x, i) => (i + 1) / 4));
    return Array.from({ length: max }, function(item, index) {
      return <div className="row" key={index}>
        {list.items.slice(0, max).map((x, i) => (
          <div className="col-3" key={i}>
            {x.val}
          </div>
        ))}
      </div>;
    });
  }

1 个答案:

答案 0 :(得分:1)

可能有很多方法可以做到这一点,但我使用lodash提出了这个解决方案:

  renderColumn(row) {
    // map through columns
    const columns = row.map(column => (
      <td key={column}>{column}</td>
    ));
    return columns;
  }
  render() {
    // Create an array of length 50
    let items = [];
    for (let i=0; i<50; i++) {
      items.push({val:i});
    }
    /** Transform the array in something like this:
     * items:   [
     *  [1, 7, 13, 19],
     *  [2, 8, 14, 20],
     *  [3, 9, 15, 21],
     *  [4, 10, 16, 22],
     *  [5, 11, 17, 23],
     *  [6, 12, 18, 24],
     * ]
     */
    // Get only 24 first items as it is a 4x6 matrix
    items = items.slice(0, 24);
    const res = _.reduce(items, (result, value, key) => {
      const index = key % 6;
      (result[index] || (result[index] = [])).push(value.val);
      return result;
    }, {});

    // map through the rows of the arrays
    const rows = _.map(res, row => {
      const column = this.renderColumn(row);
      return <tr>{column}</tr>;
    });
    return (
      <table>
        <tbody>
          {rows}
        </tbody>
      </table>
    );
  }

我希望你明白这一点:)

这是sandbox代码

相关问题