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

如何按分类标题分组展示表单项?解决分类标题重复问题

解决React表单项分类标题重复显示问题

核心思路

先将原始表单项数据按分类字段分组,把同一分类的表单项归为一组,之后遍历分组后的分类,先渲染一次分类标题,再渲染该分类下的所有表单项。

具体实现步骤

1. 数据分组处理

使用数组的reduce方法对原始JSON数据进行分组,将相同分类的表单项整合到一起:

// 示例原始表单项数据
const formItems = [
  { id: 1, label: "姓名", category: "基本信息" },
  { id: 2, label: "年龄", category: "基本信息" },
  { id: 3, label: "工作单位", category: "职业信息" },
  { id: 4, label: "职位", category: "职业信息" },
  { id: 5, label: "联系电话", category: "联系方式" }
];

// 按category字段分组
const groupedItems = formItems.reduce((acc, item) => {
  const category = item.category;
  if (!acc[category]) {
    acc[category] = [];
  }
  acc[category].push(item);
  return acc;
}, {});

2. React组件渲染

遍历分组后的对象,先渲染分类标题,再渲染对应表单项:

import React from 'react';

const FormComponent = () => {
  const formItems = [
    { id: 1, label: "姓名", category: "基本信息" },
    { id: 2, label: "年龄", category: "基本信息" },
    { id: 3, label: "工作单位", category: "职业信息" },
    { id: 4, label: "职位", category: "职业信息" },
    { id: 5, label: "联系电话", category: "联系方式" }
  ];

  // 执行分组逻辑
  const groupedItems = formItems.reduce((acc, item) => {
    const category = item.category;
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(item);
    return acc;
  }, {});

  return (
    <div className="form-container">
      {/* 遍历分组后的分类 */}
      {Object.entries(groupedItems).map(([category, items]) => (
        <div key={category} className="category-section">
          {/* 仅渲染一次分类标题 */}
          <h3>{category}</h3>
          {/* 渲染该分类下的所有表单项 */}
          <div className="form-items">
            {items.map(item => (
              <div key={item.id} className="form-item">
                <label>{item.label}</label>
                {/* 可根据需求替换为对应表单控件,如输入框、选择器等 */}
                <input type="text" placeholder={`请输入${item.label}`} />
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

export default FormComponent;

3. 样式优化(可选)

添加简单CSS区分分类区块和表单项:

.form-container {
  max-width: 600px;
  margin: 20px auto;
}

.category-section {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.category-section h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}

.form-item {
  margin: 10px 0;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-item input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

效果说明

处理后每个分类标题仅显示一次,下方对应列出该分类下的所有表单项,完全符合预期展示效果。

内容的提问来源于stack exchange,提问作者Muhammad Shafique Attari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:01:09