react antd -Form表单 (单个对象合并成整体对象) 合并对象

合并对象
[{age:‘‘12’’ },{age:‘‘11’’ },{age:‘‘13’’ }]
[{name:‘‘ss’’ },{name:‘‘aa’’ },{name:‘‘cc’’ }]
合并后 示例
[{age:‘12’, name:‘ss’},{age:‘12’, name:‘aa’},{age:‘12’, name:‘cc’},
{age:‘11’, name:‘ss’},{age:‘11’, name:‘aa’},{age:‘11’, name:‘cc’},
{age:‘13’, name:‘ss’},{age:‘13’, name:‘aa’},{age:‘13’, name:‘cc’}
]
在这里插入图片描述
对原型稍作修改
在这里插入图片描述

代码如下,其实还是要用 antd 里面的,不过是要解析数据。
重要的就是当获取了Form 后对数据的处理。
其实就是得到的数组,对数组解析。
颜色部分是一个数组对象。长度部分也是数组对象,主要就是柔和在一起称为一个新的数组。
器重你有很多的细节点,我这里直接放的是处理过的样式图代码。其中引入的组件其实是一个,只不过换了名字和里面的字段。照抄就行。

      <ElCard key='detail' id='detail' title='销售属性'>
          <div>
            {/* 颜色-长度 */}
            <Form
              ref={this.commodityRef}
              size='small'
              onValuesChange={(changedValues) => {
                console.log(changedValues);
              }}
            >
              <Form.Item
                name='marque'
                label='商品型号'
                rules={[{ required: true, message: '必填!' }]}
                style={{ width: '200px' }}
              >
                <Input />
              </Form.Item>
              <div
                style={{
                  display: 'flex',
                  width: '100%',
                  justifyContent: 'space-around'
                }}
              >
                <div style={{ width: '50%' }}>
                  <div className='content'>
                    <Form.List name='shopColorKey'>
                      {(fields, { add, remove }) => {
                        this.shouldColorRef = {
                          add,
                          remove
                        };
                        return (
                          <>
                            {fields.map(({ key, name, ...restField }) => (
                              <ShopComColor
                                key={key}
                                name={name}
                                restField={restField}
                                remove={remove}
                                form={this.commodityRef.current}
                              />
                            ))}
                          </>
                        );
                      }}
                    </Form.List>
                  </div>
                  <div className='actions' style={{ marginBottom: '5px' }}>
                    <ElButton
                      text='新增颜色'
                      handleClick={this.addShouldColor}
                    />
                  </div>
                </div>
                <div style={{ width: '50%' }}>
                  <div className='content'>
                    <Form.List name='shopLengthKey'>
                      {(fields, { add, remove }) => {
                        this.shouldLengthRef = {
                          add,
                          remove
                        };
                        return (
                          <>
                            {fields.map(({ key, name, ...restField }) => (
                              <ShopLength
                                key={key}
                                name={name}
                                restField={restField}
                                remove={remove}
                                form={this.commodityRef.current}
                              />
                            ))}
                          </>
                        );
                      }}
                    </Form.List>
                  </div>
                  <div className='actions' style={{ marginBottom: '5px' }}>
                    <ElButton
                      text='新增长度'
                      handleClick={this.addShouldLength}
                    />
                  </div>
                </div>
              </div>
            </Form>
          </div>
          <EditTable
            onRef={(ref) => (this.editTableRef = ref)}
            editTableRef={this.editTableRef}
            formRef={this.commodityRef}
            dataSource={this.state.dataSource}
            id={this.state.id}
          />
        </ElCard>

组件部分 (就放一个,都一样,换换名字)

import React, { Component } from 'react';
import { Col, Form, Row, FormInstance, Input, Button } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import request from '@/utils/request';

interface Props {
  name: number;
  restField: any;
  remove: Function;
  form: FormInstance;
}

interface State {
  CustomValueLoading: boolean;
}

export default class ShouldPayRow extends Component<Props, State> {
  CustomKeyValueue = '';
  constructor(props) {
    super(props);
    this.state = {
      CustomValueLoading: false
    };
  }

  componentDidMount() {
    console.log(this.props.form.getFieldValue(['shopColorKey']));
  }
  render() {
    const { name, restField, remove } = this.props;

    return (
      <div>
        <div
          style={{
            width: '100% ',
            display: 'flex',
            justifyContent: 'left'
          }}
        >
          <Row>
            <Form.Item
              {...restField}
              name={[name, 'ColorName']}
              label='颜色'
              style={{
                width: '150px'
              }}
            >
              <Input placeholder='颜色'></Input>
            </Form.Item>
            <MinusCircleOutlined
              style={{
                marginTop: '5px',
                marginLeft: '5px',
                marginRight: '5px'
              }}
              onClick={() => remove(name)}
            />
          </Row>
        </div>
      </div>
    );
  }
}

然后你就找到你们自己写的点击新增的位置,添加处理
// 新增

  handleRecCreate = async (rowKeys, rows) => {
    console.log(
      this.props.editTableRef, // 得到的是表格的方法
      this.props.formRef?.current?.getFieldsValue()  // 得到的是form表单的方法(获取我们需要的信息)
    );
    let ColorLength = this.props.formRef?.current?.getFieldsValue();
    await this.props.formRef?.current.validateFields().catch(() => {
      ElNotification({
        type: 'warning',
        message: '请检查必填项'
      });
      return Promise.reject();
    });
    const shopValue = await this.props.formRef?.current?.validateFields();
    // 如果在新增的时候发现表单有重复的名称就给警告
    const { shopLengthKey, shopColorKey } = shopValue;
    const groupsColor = {};
    const groupslength = {};
    shopLengthKey.forEach((item, i) => {
      const groupIdLength = item?.id || i;
      groupslength[groupIdLength] = groupslength[groupIdLength] || [];
      groupslength[groupIdLength].push(item.lengthValue);
    });
    let namesLength = shopLengthKey.map((item) => item['lengthValue']);
    let nameSetLength = new Set(namesLength);
    if (nameSetLength.size !== namesLength.length) {
      ElNotification({
        type: 'error',
        message: '有重复的长度数据值,请修改'
      });
    }
    shopColorKey.forEach((item, i) => {
      const groupIdColor = item?.id || i;
      groupsColor[groupIdColor] = groupsColor[groupIdColor] || [];
      groupsColor[groupIdColor].push(item.ColorName);
    });
    let namesColor = shopColorKey.map((item) => item['ColorName']);
    let nameColorSet = new Set(namesColor);
    if (nameColorSet.size !== namesColor.length) {
      ElNotification({
        type: 'error',
        message: '有重复的颜色数据值,请修改'
      });
    }

最主要的就是在这里了, 把数组中多个单个的对象合并成一个对象
    let newArr4 = [];
    if (
      ColorLength?.shopColorKey.length > 0 &&
      ColorLength?.shopLengthKey.length > 0
    ) {
      ColorLength?.shopColorKey?.map((item, index) => {
        if (item !== undefined) {
          ColorLength?.shopLengthKey.map((v, i) => {
            if (v !== undefined) {
              newArr4.push({
                id: maths.genFakeId(-1),
                marque: ColorLength.marque,
                ColorName: item.ColorName,
                lengthValue: v.lengthValue
              });
            } else {
              newArr4.push({
                id: maths.genFakeId(-1),
                marque: ColorLength.marque,
                ColorName: item.ColorName,
                lengthValue: 0
              });
            }
          });
        }
      });
    } else if (
      ColorLength?.shopColorKey.length === 0 &&
      ColorLength?.shopLengthKey.length === 0
    ) {
      newArr4.push({
        id: maths.genFakeId(-1),
        marque: ColorLength.marque,
        ColorName: '',
        lengthValue: 0
      });
    } else {
      if (
        ColorLength?.shopColorKey.length > 0 &&
        ColorLength?.shopLengthKey.length === 0
      ) {
        ColorLength?.shopColorKey.map((item) => {
          if (item) {
            newArr4.push({
              id: maths.genFakeId(-1),
              marque: ColorLength.marque,
              ColorName: item.ColorName,
              lengthValue: 0
            });
          }
        });
      } else {
        if (
          ColorLength?.shopColorKey.length === 0 &&
          ColorLength?.shopLengthKey.length > 0
        ) {
          ColorLength?.shopLengthKey.map((item) => {
            newArr4.push({
              id: maths.genFakeId(-1),
              marque: ColorLength.marque,
              ColorName: '',
              lengthValue: item.lengthValue
            });
          });
        }
      }
    }
    // 对数据进行过滤处理
    const filterRows = newArr4.filter((item, index, self) => {
      return self.indexOf(item.ColorName) === -1;
    });
    await this.props.editTableRef?.quitEditState(); // 停止编辑
    await this.props.editTableRef.clearRows(); // 清空表格
    await this.props.editTableRef.addRows(filterRows); // 添加新的表格数据
    // this.props.editTableRef.addRow({
    //   id: maths.genFakeId(-1)
    // });
  };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值