代码之家  ›  专栏  ›  技术社区  ›  kyun

反应动态表创建

  •  -1
  • kyun  · 技术社区  · 7 年前

    反应 .

    我可以生成一个包含这个月日期的数组。

    如果我遗漏了什么,请留言。

    class Calendar extends Component{
    
      /* ... */
    
      render(){
        let data = ["", "", "", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ""]
        return(
          <table>
            <thead>
              <tr>
                <th>S</th>
                <th>M</th>
                <th>T</th>
                <th>W</th>
                <th>T</th>
                <th>F</th>
                <th>S</th>
              </tr>
            </thead>
            <tbody>
              /* insert here dynamic data */
              /*
                <tr>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td>1</td>
                  <td>2</td>
                  <td>3</td>
                </tr>
              */
            </tbody>
          </table>
        )
      }
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Hemadri Dasari    7 年前

    所以通常要迭代一个值数组并显示它们。你应该做如下的事情,但如果你觉得这是不合理的逻辑,请道歉。

    class Calendar extends Component{
    
      /* ... */
    
      render(){
        let rows = [];
        let columns = [];
        let data = ["", "", "", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ""]
        for(let i=0; i < data.lenth; i++){
           columns.push(<td key={i}>data[i]</td>);
           if(i == 6){
              rows.push(<tr>{columns}</tr>);
              columns = [];
           }
           if(i == 13){
              rows.push(<tr>{columns}</tr>);
              columns = [];
           }
           if(i == 20){
              rows.push(<tr>{columns}</tr>);
              columns = [];
           }
           if(i == 27){
              rows.push(<tr>{columns}</tr>);
              columns = [];
           }
           if(i == 34){
              rows.push(<tr>{columns}</tr>);
              columns = [];
           }
        }
    
        return(
          <table>
            <thead>
              <tr>
                <th>S</th>
                <th>M</th>
                <th>T</th>
                <th>W</th>
                <th>T</th>
                <th>F</th>
                <th>S</th>
              </tr>
            </thead>
            <tbody>
              {rows}
            </tbody>
          </table>
        )
      }
    }
    
        2
  •  1
  •   theneuetimes    7 年前

    使用循环显示数组中的所有元素。

    <tr>
    {[...data].map((x, i) => (
        <td key={i}>{x}</td>
    ))}
    </tr>