在React的每一行中呈现表数据

时间:2019-11-24 00:27:06

标签: reactjs

我需要显示此表:table format

这样反应。我创建了一个对象数组,就像一个API

products: [
    {b: "brand1", N: "N1", M: "M1", B: "B1", S: "y1", O: "y1", A: "y1", D: "y1"},
    {b: "brand2", N: "N2", M: "M2", B: "B2", S: "y2", O: "y2", A: "y2", D: "y2"},
    {b: "brand3", N: "N3", M: "M3", B: "B3", S: "y3", O: "y3", A: "y3", D: "y3"},
    {b: "brand4", N: "N4", M: "M4", B: "B4", S: "y4", O: "y4", A: "y4", D: "y4"},
]

如何使用React以所需的格式显示此数据?

这是我为显示类似图片而尝试过的代码。

import React, { Component } from 'react';
import './results.css'

class Results extends Component {
  constructor(props){
     super(props);
     this.state = {
      products: [
        {b: "brand1", N: "N1", M: "M1", B: "B1", S: "y1", O: "y1", A: "y1", D: "y1"},
        {b: "brand2", N: "N2", M: "M2", B: "B2", S: "y2", O: "y2", A: "y2", D: "y2"},
        {b: "brand3", N: "N3", M: "M3", B: "B3", S: "y3", O: "y3", A: "y3", D: "y3"},
        {b: "brand4", N: "N4", M: "M4", B: "B4", S: "y4", O: "y4", A: "y4", D: "y4"},

    }
  }
  renderData = () => {
    return this.state.products.map((product, index)=> {
        const {M, B, S, O, A, D} = product;
        return (
          <div>    
            <tr>
              <th>A</th>
              <td>{ O }</td>
            </tr>

            <tr>
              <th>F</th>
              <td>{ B }</td>
            </tr>

            <tr>
              <th>S</th>
              <td>{ S }</td>
            </tr>

            <tr>
              <th>O</th>
              <td>{ O }</td>
            </tr>

            <tr>
              <th>A</th>
              <td>{ A }</td>
            </tr>
            <tr>
              <th>D</th>
              <td>{ D }</td>
            </tr>
          </div>
        )
    })
  }

  renderTableHeader = () => {
    return this.state.products.map((product, index)=> {
      const { b } = product;
      return <th>{ b.toUpperCase() }</th>
    })
  }

  render() {
    if (!this.props.done) {
      return null;
    }

    if (true) {
      return (
          <React.Fragment>
            <div>
              <table id="products">
                  <tbody>
                    <tr>
                      <th></th>
                      { this.renderTableHeader() }
                    </tr>
                  { this.renderData() }
                  </tbody>
              </table>      
            </div>
          </React.Fragment>
      )
    }
  }
}

这会将每个数组呈现为不同的行。

1 个答案:

答案 0 :(得分:0)

您似乎需要对数据进行一些转换才能以所需的方式显示它。当前,private static <T extends PacketListener> void a(Packet<T> packet, /* changed here -> */ T packetlistener) { packet.handle(packetlistener); } 看起来已经从您要查找的布局中移调了(尽管也许将每个品牌排成一行而不是一列可能是个好主意)。我们可以通过products方法(或在您处理获取/更新constructor的任何地方)执行此操作。

数据以正确的格式显示后,应该更清楚如何获取所需的布局。您只需要为数据的每一行创建一个products元素。每行每一列应包含一个tr元素。

例如:

td