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

React Final Form如何实现为每个customer单独添加子hotspots表单

解决方案

核心修改逻辑

  • 首先将原来全局的Add Hotspot按钮移动到每个customer的渲染区块内,绑定当前customer的数组索引和id参数
  • 修改hotspots对应的FieldArray字段路径,从根路径hotspots改为对应customer的子字段路径customers[索引值].hotspots
  • 调整添加热点时的字段操作逻辑和新热点默认值生成规则

具体代码修改

1. 修改customer列表渲染部分的代码

在customers对应的FieldArray渲染逻辑中,每个customer项的内部加入专属的hotspots管理代码,替代原来全局的hotspots逻辑:

// 原customers循环渲染的内部,customer信息展示完成后添加以下代码
{customer && (
  <div className="hotspots-wrapper" style={{marginLeft: '20px', padding: '10px', border: '1px solid #eee'}}>
    <h4>当前客户热点列表</h4>
    <FieldArray name={`customers[${index}].hotspots`}>
      {({ fields }) => (
        <>
          {fields.map((hotspotName, hotspotIndex) => (
            <div key={hotspotIndex} className="hotspot-item">
              <Field name={`${hotspotName}.positionX`} component="input" placeholder="X坐标" />
              <Field name={`${hotspotName}.positionY`} component="input" placeholder="Y坐标" />
              <button type="button" onClick={() => fields.remove(hotspotIndex)}>删除热点</button>
            </div>
          ))}
          {/* 原第174行的添加按钮逻辑迁移到此处 */}
          <button 
            type="button"
            onClick={() => {
              const newHotspot = {
                hotspotId: Date.now(), // 用时间戳生成唯一id即可
                positionY: `XhostspotforcustomerID${customer.id}`,
                positionX: `YhostspotforcustomerID${customer.id}`
              }
              fields.push(newHotspot)
            }}
          >
            给当前客户添加Hotspot
          </button>
        </>
      )}
    </FieldArray>
  </div>
)}

2. 清理冗余代码

删除原来全局定义的根路径hotspots对应的FieldArray和全局添加按钮,避免字段冲突。

效果验证

修改完成后,点击对应客户下的添加按钮,热点数据会自动挂载到当前客户对象的hotspots数组下,最终生成你需要的目标数据结构。

内容的提问来源于stack exchange,提问作者S.M. Pat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:48:01