React 最终表格如何添加 child 表格

React final forms how to add child forms

让沙盒与有效的 React 表单数组 https://codesandbox.io/s/react-final-form-field-arrays-react-beatiful-dnd-as-drag-drop-forked-uz24z?file=/index.js:5933-6061

点击添加热点并生成数据树的结果为

 {
   "toppings":[
      
   ],
   "customers":[
      {
         "id":4,
         "firstName":"name",
         "lastName":"lastname"
      },
      {
         "id":5,
         "firstName":"Clark",
         "lastName":"kent"
      }
   ],
   "hotspots":[
      {
         "hotspotId":6,
         "positionY":"Xhostspotforcustomer1",
         "positionX":"Yhostspotforcustomer1"
      }
   ]
}

但是我需要在单击“添加热点”按钮时将热点添加为客户的 children(到 values.customers 数组的相同索引),例如

{
   "toppings":[
      
   ],
   "customers":[
      {
         "id":4,
         "firstName":"name",
         "lastName":"lastname",
         "hotspots":[
            {
               "hotspotId":6,
               "positionY":"XhostspotforcustomerID4",
               "positionX":"YhostspotforcustomerID4"
            },
            {
               "hotspotId":7,
               "positionY":"more XhostspotforcustomerID4",
               "positionX":"new YhostspotforcustomerID4"
            }
         ]
      },
      {
         "id":5,
         "firstName":"Clark",
         "lastName":"kent",
         "hotspots":[
            {
               "hotspotId":8,
               "positionY":"XhostspotforcustomerID5",
               "positionX":"YhostspotforcustomerID5"
            }
         ]
      }
   ],
   
}

添加热点添加到 index.js 的第 174 行 如何修改代码为每个客户单独添加热点?

您需要将客户字段名称与热点名称结合起来:

  • 当你做 push/pop:
push(`${name}.hotspots`, /*...*/)
//...
pop(`${name}.hotspots`)
  • 同样在 FieldArray 字段名称中:
<FieldArray name={`${name}.hotspots`}>

演示:https://codesandbox.io/s/react-final-form-field-arrays-react-beatiful-dnd-as-drag-drop-forked-wivwu?file=/index.js

结果:

{
  "toppings": [],
  "customers": [
    {
      "id": 4,
      "firstName": "name",
      "lastName": "lastname",
      "hotspots": [
        {
          "hotspotId": 6,
          "positionY": "Customer4-Y1",
          "positionX": "Customer4-X1"
        },
        {
          "hotspotId": 7,
          "positionY": "Customer4-Y2",
          "positionX": "Customer4-X2"
        }
      ]
    },
    {
      "id": 5,
      "firstName": "Clark",
      "lastName": "kent",
      "hotspots": [
        {
          "hotspotId": 8,
          "positionY": "Customer5-Y1",
          "positionX": "Customer5-X1"
        }
      ]
    }
  ]
}