
在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>通过简单的代码修改,即可解决此问题,无需等待官方修复。
以上就是Ant Design List嵌套Collapse组件,子项为空时标题显示异常怎么办?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号