简体   繁体   English

在 React 中,如何使 html 表格的 tbody 可滚动?

[英]In React, how do I make the tbody of an html table scrollable?

for context I'm using React, Node, Express, Postgres to pull data from a db.对于上下文,我使用 React、Node、Express、Postgres 从数据库中提取数据。

I have an html table in a div that spans across the entire screen.我在跨越整个屏幕的 div 中有一个 html 表。 The only way I could succeed in making just the table scrollable I had to add display: block to the header and body sections.我可以成功使表格可滚动的唯一方法是我必须将display: block添加到标题和正文部分。 The problem was this floated my table to the left so the header and body sections weren't aligned.问题是这使我的表格向左浮动,因此标题和正文部分未对齐。

Table in question:有问题的表:

<h1>Inventory</h1>
        <div id="Inventory">
            <table className="table" id="InventoryTable">
                <thead id="InventoryHead">
                    <tr>
                        <th>Material</th>
                        <th>Thickness</th>
                        <th>Width</th>
                        <th>Length</th>
                        <th>Quantity</th>
                        <th>Supplier ID</th>
                    </tr>
                </thead>
                <tbody id="InventoryBody">
                    {inventory.map(inventory => (
                            <tr key={inventory.inventory_id}>
                                <td>{inventory.inventory_material}</td>
                                <td>{inventory.inventory_thickness}</td>
                                <td>{inventory.inventory_width}</td>
                                <td>{inventory.inventory_length}</td>
                                <td>{inventory.inventory_quantity}</td>
                                <td>{inventory.supplier_id}</td>
                            </tr>
                        ))}   
                </tbody>
            </table>
            
        </div>

CSS used:使用的 CSS:

#Inventory {
  overflow: scroll;
  max-height: 300px;
}

Please let me know if there's more info I can provide, thanks!如果我可以提供更多信息,请告诉我,谢谢!

So far I have tried to use display: block to be able to scroll just the tbody.到目前为止,我已经尝试使用display: block来滚动 tbody。 This worked, but it also broke the table structure.这行得通,但它也破坏了表结构。 As a workaround I applied overflow: scroll to the div instead, but this isn't ideal because the table header gets scrolled as well.作为一种解决方法,我应用了overflow: scroll到 div,但这并不理想,因为表头也会滚动。

只需给出表格宽度#InventoryTable { width: 100% }

You can give width of 100% and specify the scroll if you want scroll in horizontal position then overflow-x:scroll.如果要在水平位置滚动,则可以指定 100% 的宽度并指定滚动,然后使用 overflow-x:scroll。 If you want scroll vertically then overflow-y:scroll.如果你想垂直滚动然后溢出-y:滚动。

#InventoryBody {
Width: 100%;
Overflow-x: scroll;
}

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

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