首页 > 解决方案 > React-Hooks:如何创建可重用的数据表组件?

问题描述

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

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

标签: reactjsdatatablereact-hooksreact-component

解决方案


这可能会有所帮助

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>

推荐阅读