0

让沙箱与有效的 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"
      }
   ]
}

但是当单击“添加热点”按钮(到 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 行添加的 如何修改代码以分别为每个客户添加热点?

4

1 回答 1

1

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

  • 当你推/弹出:
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"
        }
      ]
    }
  ]
}
于 2021-11-05T14:31:06.100 回答