You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:02:58