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

如何在React.js中实现带增删改功能的递归分类列表组件?

实现带多层子分类的可操作列表方案

先搞定数据结构

用嵌套数组对象存储多层分类,每个分类包含名称和子分类数组,示例:

const categories = [
  {
    name: 'Breakfast',
    children: [
      {
        name: 'Egg Types',
        children: [{ name: 'Some of name' }]
      }
    ]
  },
  {
    name: 'Lunch',
    children: [
      {
        name: 'Chicken',
        children: [{ name: 'Some of name' }]
      }
    ]
  }
];

增删改功能实现

添加分类

明确要添加的父分类层级(用数组表示路径,比如['Breakfast', 'Egg Types']),遍历找到目标父分类后,将新分类推入其children数组:

function addCategory(parentPath, newName) {
  let target = categories;
  for (const name of parentPath) {
    target = target.find(item => item.name === name)?.children;
    if (!target) return; // 未找到父分类,终止操作
  }
  target.push({ name: newName, children: [] });
}

编辑分类

根据层级路径找到目标分类,直接修改其name属性:

function editCategory(path, newName) {
  let target = categories;
  for (let i = 0; i < path.length - 1; i++) {
    target = target.find(item => item.name === path[i])?.children;
    if (!target) return;
  }
  const category = target.find(item => item.name === path[path.length - 1]);
  if (category) category.name = newName;
}

删除分类

找到目标分类的父级,从父级的children数组中过滤掉该分类:

function deleteCategory(path) {
  let target = categories;
  for (let i = 0; i < path.length - 1; i++) {
    target = target.find(item => item.name === path[i])?.children;
    if (!target) return;
  }
  target = target.filter(item => item.name !== path[path.length - 1]);
}

渲染成示例样式(React为例)

用递归组件渲染层级结构,同时带上操作按钮,展示成分类>子分类>子子分类的格式:

function CategoryItem({ category, path = [] }) {
  const fullPath = [...path, category.name].join(' > ');
  return (
    <div>
      <span>{fullPath}</span>
      <button onClick={() => {
        const newName = prompt('输入新分类名称');
        newName && editCategory([...path, category.name], newName);
      }}>编辑</button>
      <button onClick={() => deleteCategory([...path, category.name])}>删除</button>
      <button onClick={() => {
        const newName = prompt('输入新子分类名称');
        newName && addCategory([...path, category.name], newName);
      }}>加子分类</button>
      {/* 递归渲染子分类,缩进区分层级 */}
      {category.children.length > 0 && (
        <div style={{ marginLeft: '20px' }}>
          {category.children.map(child => (
            <CategoryItem key={child.name} category={child} path={[...path, category.name]} />
          ))}
        </div>
      )}
    </div>
  );
}

// 整体列表组件
function CategoryList() {
  return (
    <div>
      <button onClick={() => {
        const newName = prompt('输入一级分类名称');
        newName && addCategory([], newName);
      }}>加一级分类</button>
      {categories.map(category => (
        <CategoryItem key={category.name} category={category} />
      ))}
    </div>
  );
}

内容的提问来源于stack exchange,提问作者Switch To React

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:18:24