首页 > 解决方案 > React Typescript列表映射表行未呈现

问题描述

我有一个称为项目的对象列表。我想将列表中的每个对象放到表中的一行。但是,这些行没有被呈现。我正在使用带有 react-bootstrap 的打字稿。我想知道为什么会发生这种情况以及如何解决它。谢谢!

模板.tsx

export default function Templates() {
    const items = [
        {
          "name": "Item 1",
          "alt": "First",
          "description": "This is the first item"
        },
        {
          "name": "Item 2",
          "alt": "Second",
          "description": "This is the second item"
        },
        {
          "name": "Item 3",
          "alt": "Third",
          "description": "-"
        }
      ]
    return (
        <>
            <MyTable items={items}>MyTable</MyTable>
        </>
    )
}

我的表.tsx

import React from 'react'
import { Table, Button } from 'react-bootstrap'

type TableProps = {
    items: {
        name: string,
        alt: string,
        description: string
    }[]
}
const MyTable: React.FunctionComponent<TableProps> = ({
    items
  }) => {
    return (
        <>
            <Table striped bordered hover variant="dark">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Alt</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    {items.map(item => {
                        <tr>
                            <td>{item.name}</td>
                            <td>{item.alt}</td>
                            <td>{item.description}</td>
                        </tr>
                    })}
                </tbody>
            </Table>
        </>
        )
  };

export default MyTable;

现在只渲染了thead。

标签: reactjstypescriptreact-bootstrap

解决方案


您正在映射项目并且映射回调返回未定义(无返回语句),请确保返回迭代项目:

     {items.map(item => {
          return (
            <tr key={item.name}>
              <td>{item.name}</td>
              <td>{item.alt}</td>
              <td>{item.description}</td>
            </tr>
          )
        })}

推荐阅读