如何使用MUI Typography组件实现嵌套缩进文本列表
实现MUI嵌套缩进列表的解决方案
问题背景
我原本使用扁平数组存储列表数据:
const bullets = [ "Top Sports are:", "hockey", "soccer", "football", "Top Names are:", "liam", "noah", "jordan" ]
通过MUI的Typography组件可以生成普通无序列表,代码如下:
import { Typography } from 'components/Typography' //... <div > {bullets.map((bullet: string, index: any) => ( <Typography key={index} component='li' variant='body2'> {bullet} </Typography> ) )} </div>
现在将数据结构改为嵌套数组形式:
const nestedBullets = [ "Top Sports are:", ["hockey","soccer","football"], "Top Names are:", ["liam","noah","jordan"] ]
需要修改代码,实现带有缩进的嵌套列表效果,最终样式如下:
- Top Sports are: - hockey - soccer - football - Top Names are: - liam - noah - jordan
修改后的代码
import { Typography } from 'components/Typography' //... <div> {nestedBullets.map((item, index) => { // 判断当前项是否为子列表数组 if (Array.isArray(item)) { return ( <Typography key={index} component="ul" variant="body2" sx={{ paddingLeft: 2, margin: 0 }} > {item.map((subItem, subIndex) => ( <Typography key={subIndex} component="li" variant="body2"> {subItem} </Typography> ))} </Typography> ) } // 渲染主列表项 return ( <Typography key={index} component="li" variant="body2"> {item} </Typography> ) })} </div>
关键说明
- 遍历
nestedBullets时,用Array.isArray()区分主标题文本和子列表数组 - 主标题直接渲染为
<li>元素(通过Typography的component属性指定) - 子列表数组渲染为
<ul>元素,通过sx属性设置paddingLeft实现缩进,同时去掉默认margin避免多余间距 - 为每个渲染的元素设置唯一
key,示例中使用索引,实际项目建议使用数据自身的唯一标识
内容的提问来源于stack exchange,提问作者guy
相关产品推荐
相关产品推荐

