React-Hooks:如何创建可重用数据 table 组件?

React-Hooks: How to create reusable data table component?

在我的应用程序中,我需要可重用数据 table 组件。我可以在哪里更改 table-header & table-body 动态内容。

 <table className="table table-hover">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Publish Date</th>
                    </tr>
                </thead>
                <tbody>
                    {data &&
                        data.map(item => (
                            <tr key={item.id}>
                                <td>{item.id}</td>
                                <td>{item.image}</td>
                                <td>{item.title}</td>
                                <td>{item.publishDate}</td>
                            </tr>
                        ))}
                </tbody>
            </table>

这可能有帮助

const CustomTable = ({header, posts}) => {
    return (
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>{header.image}</th>
                    <th>{header.title}</th>
                    <th>{header.publishedDate}</th>
                </tr>
            </thead>
            <tbody>
                {posts &&
                    posts.map(item => (
                        <tr key={item.id}>
                            <td>{item.id}</td>
                            <td>{item.image}</td>
                            <td>{item.title}</td>
                            <td>{item.publishDate}</td>
                        </tr>
                    ))}
            </tbody>
        </table>
    );
}

您可以传递 header 并在任何需要的地方发布数组。

<div className='table'>
    <CustomTable header={header} posts={posts} />
</div>

看看这是否有效! https://stackblitz.com/edit/react-ie2rt6

import React from "react";

const Table = ({ headers, data }) => {
  return (
    <div>
      <table>
        <thead>
          <tr>
            {headers.map(head => (
              <th>{head}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map(row => (
            <tr>
              {headers.map(head => (
                <td>{row[head]}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default Table;