簡體   English   中英

在表中反應 typescript 通用映射

[英]React typescript generic mapping in table

我想創建一個通用表,可以 map 行不同的接口。

假設我有以下接口:

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

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

現在我想把它們放在一個像這樣的 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>

如何對 rows1 和 rows2 使用相同的 tbody,而不是創建兩個單獨的 tbody? 即,重用相同的組件。

我想您只想創建單個組件,但能夠根據給定的行和 header 相應地改變列的數量。

這是我的解決方案(手寫,可能有錯字)。

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>
  );
}

重用組件:

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