
在ant design的list组件中嵌套collapse组件时,可能会遇到一个显示问题:当collapse组件的子项为空时,标题显示异常。本文将分析此问题并提供解决方案。
问题:
在PC端网站开发中,使用Ant Design的List组件,并在renderItem函数中返回Collapse组件。当Collapse组件的子项item.children为空数组时,Collapse标题显示错误。
示例代码片段(问题代码):
<Collapse
key={item.id}
title={item.title}
expandIconPosition="end"
ghost
showArrow={item.children.length} // 问题所在
>
{item.children.map((child) => (
<div
key={child.id}
onClick={() => {
handleHelpInfo(child);
}}
style={{ cursor: 'pointer', marginBottom: 10, background: token.bgColorPrimary, padding: 4 }}
>
{child.title}
</div>
))}
</Collapse>
当item.children.length为0时,showArrow属性的值也为0,导致Collapse标题显示异常。
解决方案:
问题并非Ant Design组件本身的bug,而是代码逻辑问题。showArrow属性的值应根据item.children是否存在来决定,而不是直接使用其长度。 只需将showArrow={item.children.length}修改为showArrow={!!item.children.length}。
!!操作符将item.children.length转换为布尔值:当item.children.length为0时,!!item.children.length为false;否则为true。 这样就能正确控制Collapse标题的箭头是否显示。
修改后的代码:
<Collapse
key={item.id}
title={item.title}
expandIconPosition="end"
ghost
showArrow={!!item.children.length} // 修改后的代码
>
{item.children.map((child) => (
<div
key={child.id}
onClick={() => {
handleHelpInfo(child);
}}
style={{ cursor: 'pointer', marginBottom: 10, background: token.bgColorPrimary, padding: 4 }}
>
{child.title}
</div>
))}
</Collapse>
通过简单的代码修改,即可解决此问题,无需等待官方修复。










