React中使用Bootstrap实现带多层嵌套Accordion的HTML表格及问题排查
Hey there! Let’s break down your two issues and fix them up:
1. Table borders not appearing despite using table-bordered
What’s causing this?
A few things are getting in the way here:
- Missing
table-borderedon nested tables: Bootstrap’stable-borderedonly applies to the specific table you add it to. Your inner tables (the green and blue ones) don’t have this class, so their cells won’t show borders. - Incorrect
colSpanvalue: Your collapse rows usecolSpan={12}, but your main table only has 4 columns. This mismatch messes up the layout and can break border rendering. - Duplicate IDs: You have multiple tables with the same
id(likesecondTableandthirdTablerepeated). While this doesn’t directly break borders, it’s invalid HTML and can cause unexpected behavior down the line—especially important if you plan to generate this dynamically later.
Quick fix steps:
- Add
table-borderedto every nested table. For example:// Before <table className="table" id="secondTable"> // After <table className="table table-bordered" id="secondTable-1"> - Correct the
colSpanto match your table’s actual column count (4, not 12):<td colSpan={4}> - Update all duplicate IDs to be unique (use something like
secondTable-${index}if you’re looping dynamically later).
2. Stop other accordions from closing when opening one
Why this is happening
Bootstrap’s data-bs-parent attribute is designed to make accordions mutually exclusive—when you open one collapsible element under that parent, all others close automatically. That’s exactly what’s happening with your current setup.
How to fix it
If you want multiple accordions to stay open at the same time, remove the data-bs-parent attribute entirely from all your trigger rows and collapse rows.
For example, change this:
<tr data-bs-toggle="collapse" data-bs-target="#main-accordion1" data-bs-parent="#firstTable">
To this:
<tr data-bs-toggle="collapse" data-bs-target="#main-accordion1">
And remove data-bs-parent="#firstTable" from the corresponding collapse row too:
<tr className="collapse accordion-collapse" id="main-accordion1">
Repeat this for all nested accordion triggers and collapse elements (the green ones in your second table).
If later you want some groups to be mutually exclusive (but not all), you can split them into separate parent containers. But for your current goal of keeping multiple accordions open, removing data-bs-parent is the simplest solution.
内容的提问来源于stack exchange,提问作者vincent

