【问题标题】:React-Hooks: How to create reusable data table component?React-Hooks:如何创建可重用的数据表组件?
【发布时间】:2020-12-21 05:58:35
【问题描述】:

在我的应用程序中,我需要可重用的数据表组件。我可以在哪里使用动态内容更改表头和表体。

 <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>

【问题讨论】:

    标签: reactjs datatable react-hooks react-component


    【解决方案1】:

    看看这是否有效! 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;
    

    【讨论】:

    【解决方案2】:

    这可能会有所帮助

    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 和 posts 数组。

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

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 1970-01-01
      • 2021-07-11
      • 2018-08-24
      • 1970-01-01
      • 2021-04-01
      • 2019-07-29
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多