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

React中如何使用含任意层级子项的对象创建嵌套菜单组件

实现方案

核心用递归逻辑处理树形嵌套结构,不需要写死多层循环,就能适配任意层级的子项渲染,每一层的渲染逻辑完全复用即可。

核心逻辑

封装一个独立的渲染单元(函数/组件),接收数组类型的菜单列表作为入参:

  • 遍历当前传入的数组,为每一项渲染<li>标签,内部先放置包含name字段的<a>标签
  • 判断当前项的children数组是否存在且长度大于0,如果满足条件,就在当前<li>内部嵌套调用当前封装的渲染单元,将当前项的children作为入参传入,外层用<ul>包裹递归返回的内容
  • 最外层调用封装的渲染单元,传入根级的Data数组即可得到最终的菜单结构

如果需要根据数据里的show字段控制项是否显示,只需要在遍历项的时候增加判断条件item.show !== false即可,未配置show字段的项默认渲染。

各技术栈实现示例

React 实现

// 递归菜单组件
const Menu = ({ list }) => {
  return (
    <ul>
      {list.map((item, idx) => (
        <li key={idx}>
          <a>{item.name}</a>
          {item.children?.length > 0 && <Menu list={item.children} />}
        </li>
      ))}
    </ul>
  )
}

// 外层调用
<Menu list={Data} />

Vue 实现

首先创建递归组件Menu.vue:

<template>
  <ul>
    <li v-for="(item, idx) in list" :key="idx">
      <a>{{ item.name }}</a>
      <Menu v-if="item.children?.length" :list="item.children" />
    </li>
  </ul>
</template>
<script>
export default {
  name: 'Menu',
  props: {
    list: {
      type: Array,
      required: true
    }
  }
}
</script>

业务组件内调用:

<template>
  <Menu :list="Data" />
</template>

原生JS实现

function renderMenu(list) {
  const ul = document.createElement('ul')
  list.forEach(item => {
    const li = document.createElement('li')
    const a = document.createElement('a')
    a.innerText = item.name
    li.appendChild(a)
    if(item.children?.length) {
      li.appendChild(renderMenu(item.children))
    }
    ul.appendChild(li)
  })
  return ul
}

// 插入到页面指定节点
document.querySelector('#app').appendChild(renderMenu(Data))

内容的提问来源于stack exchange,提问作者code0x00

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:51:02