javascript React Table -表不呈现

toiithl6  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(130)

我有一个const,应该在浏览器中显示为一个表,使用方法MAP。问题在下面(表中未显示汽车)。有人能帮忙吗?

const topCars = [
  {manufacturer:'Fiat', model:'m5'},
  {manufacturer:'Nissan', model:'e6'},
  {manufacturer:'Lexus', model:'r'}
]

我的代码:

export type NewComponentType = {
    cars: CarsType[]
}

export type CarsType = {
    manufacturer: string
    model: string
}

export const NewComponents = (props: NewComponentType) => {
    return (
        <>
            {props.cars.map((objectFromCarsTypeArray, index) => {
                return (
                    <table>
                        <thead key={index}>
                        </thead>
                        <tr>
                            <td>{objectFromCarsTypeArray.manufacturer}</td>
                            <td>{objectFromCarsTypeArray.model}</td>
                        </tr>
                    </table>
                )
            })}
        </>
    );
};

以及它在浏览器中的显示方式:

Fiat    m5
Nissan  e6
Lexus   r

尝试:重命名表标记-没有发生任何事情

hvvq6cgz

hvvq6cgz1#

1.错误显示您需要<tbody>元素来 Package 行。
1.此时,您正在为每个对象生成一个表。您需要将<table><thead><tbody>移动到map之外。
1.不要使用map的索引来生成键,而是向数据集中的对象添加id属性并使用它。

const { useState } = React;

function Cars(props) {
  return (
    <table>
      <thead>
        <tr>
          <th>Manufacturer</th>
          <th>Model</th>
        </tr>
      </thead>
      <tbody>
        {props.cars.map(obj => {
          return (
            <tr key={obj.id}>
              <td>{obj.manufacturer}</td>
              <td>{obj.model}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

const topCars = [
  { id: 1, manufacturer: 'Fiat', model: 'm5' },
  { id: 2, manufacturer: 'Nissan', model: 'e6' },
  { id: 3, manufacturer: 'Lexus', model: 'r' }
];

ReactDOM.render(
  <Cars cars={topCars} />,
  document.getElementById('react')
);
table { border-collapse: collapse; width: 50vw; }
th { text-align: left; }
td { padding: 0.25rem; border: 1px solid #efefef; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

相关问题