首页 > 解决方案 > 反应本机中的循环组件

问题描述

我想使用以下对象返回一个像表格这样的组件。但我必须只使用点数组。不需要头部标签。

const states = {
  player: [
    {
      id: 1,
      name: 'David',
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2]
    },
    {
      id: 2,
      name: 'John',
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2]
    },
    {
      id: 3,
      name: 'Sam',
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2]
    },
    {
      id: 4,
      name: 'Johanson',
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2]
    }
  ]
} 

我在 react-native-paper 中使用 DataTable。它具有这种结构;

 <DataTable>
        <DataTable.Header>
          <DataTable.Title>Dessert</DataTable.Title>
          <DataTable.Title>Calories</DataTable.Title>
          <DataTable.Title>Fat</DataTable.Title>
        </DataTable.Header>

        <DataTable.Row>
          <DataTable.Cell>Frozen yogurt</DataTable.Cell>
          <DataTable.Cell>159</DataTable.Cell>
          <DataTable.Cell>6.0</DataTable.Cell>
        </DataTable.Row>

      </DataTable>

标签: javascriptreactjsreact-native

解决方案


我会这样做:

编辑:由于您想在列而不是行中呈现点,我假设所有玩家都有相同数量的点并使用第一个玩家的点来呈现行。

const states = {
  player: [
    {
      id: 1,
      name: "David",
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2],
    },
    {
      id: 2,
      name: "John",
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2],
    },
    {
      id: 3,
      name: "Sam",
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2],
    },
    {
      id: 4,
      name: "Johanson",
      points: [3, 4, 8, 2, 5, 3, 9, 5, -4, -6, 2],
    },
  ],
};

function MyDataTable() {
  return (
    <DataTable>
      {states.player[0].points.map((p, i) => (
        <DataTable.Row key={p}>
          {states.player.map((player) => (
            <DataTable.Cell>{player.points[i]}</DataTable.Cell>
          ))}
        </DataTable.Row>
      ))}
    </DataTable>
  );
}

推荐阅读