将数组项分成一定数量的行

时间:2018-07-16 20:10:56

标签: reactjs

renderItems() {
    const {items} = this.state;
    const results = [];
    for (let i = 0; i < items.length; i++) {
      results.push(
        <tr>
          {
            for (let j = 0; j < 8; j++) {

            }
          }
        </tr>
      )
    }
  }

基本上,我有一个由32个项目组成的数组,想将其分成每行8个项目(总共为4行),但是上面的代码为<tr>内部的内部循环提供了错误,这是正确的(而且我不确定如何纠正它。)

React中动态创建4行并将8 td放入每行的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

您不能在JSX的{}内部直接使用for循环,因为它需要一个表达式。

您可以在JSX之外进行for循环,或将items数组分块为长度为8且长度为map的数组。

示例

renderItems() {
  const items = [...this.state.items];
  const chunks = [];

  while (items.length) {
    chunks.push(items.splice(0, 8));
  }

  return chunks.map(chunk => (
    <tr>{chunk.map(item => <td>{item}</td>)}</tr>
  ));
}

答案 1 :(得分:0)

这绝不是一个优雅的解决方案,但是它可以工作:

renderItems() {
    const { items } = this.state;

    // first, create all the <td> elements and store them in a list
    let allTDs = []

    for (let i = 0; i < items.length; i++) {
        allTDs.push(<td key={ items[i] }> { items[i] } </td>)
    }

    //then break the list into four rows and keep them in separate lists
    let tr1 = [];
    let tr2 = [];
    let tr3 = [];
    let tr4 = [];

    // keep count for each row
    let count = 0

    for (let td of allTDs) {
      //first eight goes to the first row, second eight to the second etc.
      if(count < 8) {
        tr1.push(td)
      } else if (count < 16) {
        tr2.push(td)
      } else if (count < 24) {
        tr3.push(td)
      } else if (count < 32) {
        tr4.push(td)
      }
      count += 1;
    }

    // bring all four rows together in a list so that you can return that list
    let allTRs = [];
    allTRs.push(tr1, tr2, tr3, tr4)

    return allTRs
  }


 render() {
    return (
      <div>
        <table>
          <tbody>

            // serve each row by calling the renderItems() method and indexing
            // the relevant row
            <tr>{ this.renderItems()[0] }</tr> 
            <tr>{ this.renderItems()[1] }</tr>
            <tr>{ this.renderItems()[2] }</tr>
            <tr>{ this.renderItems()[3] }</tr>

          </tbody>
        </table>
      </div>
    )
  }