简体   繁体   English

在表中反应 typescript 通用映射

[英]React typescript generic mapping in table

I want to create a generic table that can map rows of different interfaces.我想创建一个通用表,可以 map 行不同的接口。

Let's say I have the following interfaces:假设我有以下接口:

interface Row1{
username: string;
email: string;
}

interface Row2{
firstName: string;
lastName: string;
address: string;
age: string;
}

Now I want to map them in a tbody like this (?):现在我想把它们放在一个像这样的 tbody 中(?):

const rows1: Row1 = [{username: "tester", email: "test@test.mail"}, {username: "tester2", email: "test2@test.mail"}]
const rows2: Row2 = [{firstName: "Bob", lastName: "Bobber", address: "street", age: "22"}, {firstName: "Bill", lastName: "Gates", address: "street2", age: "55"}]

<tbody>
   {rows1?.map((row, index) => {
     return(

         <tr key={index}>
            <td>{row.username}</td>
            <td>{row.email}</td>
         </tr>
     )
   }}
</tbody>

How can I use the same tbody for both rows1 and rows2, instead of creating two separate tbodies?如何对 rows1 和 rows2 使用相同的 tbody,而不是创建两个单独的 tbody? Ie, reusing the same component.即,重用相同的组件。

I guess you want to create only single component but capable to vary the amount of columns based on the given rows and header accordingly.我想您只想创建单个组件,但能够根据给定的行和 header 相应地改变列的数量。

Here is my solution (hand-written, might have typo).这是我的解决方案(手写,可能有错字)。

The TBody component: TBody 组件:

interface TBodyProps {

  rows: {
      [key: string]: string;
  }[];

  // for denoting what headers should be shown
  // and indicating the order of the field
  headers: string[];

}

const TBody = ({ rows, headers }: TBodyProps) => {

  return (
    <tbody>
      {
        rows.map(row => (
          <tr>
            {
              headers.map(header => (
                <td>
                  {row[header]}
                </td>
              ))
            }
          </tr>
        ))
      }
    </tbody>
  );
}

Reuse the component:重用组件:

return (
  <>
    <TBody
      rows={rows1}
      headers={["username", "email"]}
    />

    <TBody
      rows={rows2}
      headers={["firstName", "lastName"]}
    />
  </>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM