Blazor动态数据源页面折叠卡片实现方案求助
Fixing Dynamic Bootstrap Collapse Cards & Homepage Redirect Issue
Dynamic Data Compatibility Fix
Ditching individual bool variables for each collapse is the way to go—use a single state to track which collapse is open. This works for any dynamic dataset:
Track the active collapse ID (example using React; adapt to your framework):
const [activeCollapse, setActiveCollapse] = useState(null);Toggle function for dynamic items:
const toggleCollapse = (faqId) => { setActiveCollapse(activeCollapse === faqId ? null : faqId); };Render dynamic FAQ cards:
{yourDynamicFAQData.map(faq => ( <div class="card" key={faq.id}> <div class="card-header" onClick={() => toggleCollapse(faq.id)}> <button class="btn btn-link">{faq.question}</button> </div> <div class={`collapse ${activeCollapse === faq.id ? 'show' : ''}`} id={`faq-collapse-${faq.id}`}> <div class="card-body">{faq.answer}</div> </div> </div> ))}
Stop the href="#" Redirect
If you’re using Bootstrap’s native data-toggle, href="#" is causing the page jump because it’s a default anchor behavior. Fix it with one of these:
Use the correct target ID in href:
<a class="btn btn-link" data-toggle="collapse" href="#faq-collapse-1" aria-expanded="false" aria-controls="faq-collapse-1"> Your Question Here </a>Swap href for data-target (better for buttons):
<button class="btn btn-link" data-toggle="collapse" data-target="#faq-collapse-1" aria-expanded="false" aria-controls="faq-collapse-1"> Your Question Here </button>Prevent default if you must use #:
document.querySelectorAll('[data-toggle="collapse"][href="#"]').forEach(el => { el.addEventListener('click', e => e.preventDefault()); });
Pro tips:
- Always generate unique IDs for dynamic collapses (like
faq-collapse-${faq.id}) to avoid conflicts. - The single state approach scales infinitely—no need to add new variables every time you add a FAQ item.
内容的提问来源于stack exchange,提问作者Talan
相关产品推荐
相关产品推荐

