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

React嵌套数组映射问题:配置器按钮生成异常求助

问题修复方案

核心问题分析

  1. 错误复用单一分类的材质数据:你通过const [{material}] = materials仅提取了数组第一个元素(Body分类)的材质列表,导致两个分类下都渲染Body的按钮,Drawer分类的材质完全未被调用。
  2. Radio控件与标签关联失效:input的id设为index,但label的htmlFor使用sections.part,点击标签无法触发对应的radio控件。

修正后的代码

const materials = [
      { 
      id: 1, 
      part: "Body",
      material: [
        {
        id: "Astra Blue",
        type: "Lacquer",
        diffuse:"image URL", 
        normal: "image URL", 
        orm: "image URL", 
        },
        {
        id: "Spring Green",
        type: "Lacquer",
        diffuse:"image URL", 
        normal: "image URL", 
        orm: "image URL", 
        },
      ],
      },
      { 
      id: 2, 
      part: "Drawer",
      material: [
        {
        id: "Dash Pink",
        type: "Lacquer",
        diffuse:"image URL", 
        normal: "image URL", 
        orm: "image URL", 
        },
        {
        id: "Weston Grasscloth",
        type: "Grasscloth",
        diffuse:"image URL", 
        normal: "image URL", 
        orm: "image URL", 
        },
      ],
      }
    ];

    return (
        <div>
        {materials.map((sections, index) => {
            return (
            <div key={sections.id}>
                <input
                type='radio'
                name='accordion'
                id={`accordion-${sections.part}`}
                className='accordion__input'/>
            <label htmlFor={`accordion-${sections.part}`} className='materialLabel'>
                {sections.part}
            </label>
            <div>
                {sections.material.map((materialName) => {
                    return (
                    <button 
                        key={materialName.id} 
                        onClick={swapBody} 
                        className='item' 
                        value={materialName.diffuse} 
                        data-value={materialName.normal}
                        data-value2={materialName.orm}>
                        {materialName.id}
                    </button>
                  );
                })}
              </div>

            </div>
            
          );
        })}
        </div>
    )

关键修改点

  • 删除多余的const [{material}] = materials代码,直接通过sections.material遍历当前分类下的材质列表
  • 统一input的id与label的htmlFor为accordion-${sections.part},确保标签与radio控件正确关联
  • 给外层循环的div添加key={sections.id},符合React列表渲染的规范要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:45:33