import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Modal, Select, Row, Col } from 'antd';

const { Option } = Select;
const FormItem = Form.Item;

@Form.create()
@connect(({ filterBlock }) => ({ filterBlock, }))
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      formVals: props.record || {},
      filterSelect: [],
      keyId: '',
    };

    this.formLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
    };

    this.formLayout1 = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    this.formLayout2 = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    // eslint-disable-next-line no-unused-vars
    const { formVals, filterSelect } = this.state;
    if (formVals.key) {
      dispatch({
        type: 'filterBlock/fetchItemsList',
        payload: formVals.key,
        callback: res => {
          if (res && res.status === 200) {
            const centerData = res.data.map(item => {
              return {
                label: item,
                value: `${item}`,
              };
            });
            this.setState({ filterSelect: centerData });
          }
        },
      });
    }
  }

  handleSave = () => {
    const { form, okChange, index, record, filterList } = this.props;
    const { formVals, keyId } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const arrData = fieldsValue.content.reduce((arr, next) => {
        const typeList = next.type.map(type => {
          return { type, name: next.name };
        });
        return arr.concat(typeList);
      }, []);

      const nameValue = (filterList || []).find(item => item.id === keyId)?.title;
      const formItem = {
        key: keyId || formVals?.key,
        value: fieldsValue?.value || nameValue,
        typeList: arrData,
      };
      console.log(formItem, 80);
      okChange(formItem, index);
      this.handleVisible();
    });
  };

  handleVisible = (flag, record) => {
    this.setState({
      visible: !!flag,
      formVals: record || {},
    });

  };

  // 添加
  add = () => {
    const { form } = this.props;
    const list = form.getFieldValue('list');
    const nextList = list?.concat({});
    form.setFieldsValue({
      list: nextList,
    });

  }

  // 删除
  deleteRow = index => {
    const { form } = this.props;
    const list = form.getFieldValue('list');
    const content = form.getFieldValue('content');

    if (list.length === 1) {
      return;
    }

    form.setFieldsValue({
      list: list.filter((item, key) => key !== index),
      content: content.filter((item, key) => key !== index),
    });
  };

  projectChange = keys => {
    const { dispatch } = this.props;
    // eslint-disable-next-line no-unused-vars
    const { filterSelect, keyId } = this.state;
    dispatch({
      type: 'filterBlock/fetchItemsList',
      payload: keys,
      callback: res => {
        if (res && res.status === 200) {
          const centerData = res.data.map(item => {
            return {
              label: item,
              value: `${item}`,
            };
          });
          this.setState({ filterSelect: centerData, keyId: keys });
        }
      },
    });

  };

  renderContent = formVals => {
    console.log(formVals, 144);
    const { filterSelect } = this.state;
    const { formLayout, formLayout1, formLayout2 } = this
    const { form: { getFieldDecorator, getFieldValue }, filterList, } = this.props;
    ;
    getFieldDecorator('list', { initialValue: Object.keys(formVals).length > 0 ? formVals.typeList : [{}], });

    const list = getFieldValue('list');
    // const list = formVals?.typeList || [{}];
    // getFieldDecorator('list', { initialValue: list });
    console.log(list, 155);
    const selectProps = {
      placeholder: '请选择',
      optionFilterProp: 'children',
      style: { width: '100%', },
      allowClear: true,
      showSearch: true,
    };

    return (
      <Form>
        <FormItem key='value' {...formLayout} label='筛选项'>
          {getFieldDecorator('value', {
            rules: [{ required: true, message: '请选择筛选项' }],
            initialValue: formVals.value,
          })(<Select {...selectProps} onChange={value => this.projectChange(value)}>
            {filterList?.length &&
              filterList?.map(items => (
                <Option
                  key={items.id}
                  value={items.id}
                  disabled={(this.props?.sourceData || []).find(item => item.key == items.id)}
                >
                  {items.title}
                </Option>
              ))}
          </Select>)}        </FormItem>
        , {(list || []).map((item, index) => {
          return (
            <Row>
              <Col span={10}>
                <FormItem label={`筛选类${index + 1}`} key={index} {...formLayout1}>
                  {getFieldDecorator(`content[${index}].type`, {
                    rules: [{
                      required: true,
                      message: '请选择筛选类!',
                    }],
                    initialValue: item.type?.split(','),
                  })(<Select {...selectProps} mode='multiple'>
                    {filterSelect.map(item1 => (
                      <Option key={item1.label} value={item1.value}>
                        {item1.label}
                      </Option>
                    ))}
                  </Select>)}                </FormItem>
              </Col>
              <Col span={10}>
                <FormItem label='别称' key={index} {...formLayout2}>
                  {getFieldDecorator(`content[${index}].name`, {
                    initialValue: item.name,
                    rules: [{
                      required: true,
                      message: '请输入别称',
                    }],
                  })(<Input placeholder='请输入' />)}                </FormItem>
              </Col>
              <Col span={4}>
                <div style={{ width: '100%', height: '27px', marginTop: '10px', marginLeft: '10px' }}>
                  {index > 0 ? (
                    <span style={{ color: '#1890FF', cursor: 'pointer' }} onClick={this.deleteRow.bind(this, index)}>删除</span>
                  ) : null}
                  {index === 0 ? (
                    <span style={{ paddingRight: '12px', color: '#1890FF', cursor: 'pointer' }} onClick={this.add}>新增</span>
                  ) : null}
                </div>
              </Col>
            </Row>
          );
        })}
      </Form>
    );
  };

  render() {
    const { children, record } = this.props;
    const { visible, formVals } = this.state;
    return (
      <>
        {React.cloneElement(children, { onClick: () => this.handleVisible(true, record), })}
        <Modal
          width={800}
          bodyStyle={{ padding: '15px 30px' }}
          destroyOnClose
          title={Object.keys(formVals).length > 0 ? '编辑' : '新建'}
          visible={visible}
          onOk={() => this.handleSave()}
          onCancel={() => this.handleVisible()}
          maskClosable={false}
        >
          {this.renderContent(formVals)}
        </Modal>
      </>
    );
  }
}

UpdateForm.defaultProps = {
  okChange: () => { },
};

export default UpdateForm;
添加筛选项到表格里面去。点击编辑的时候,新增的就没展示数据出来,这是为什么,renderContent = formVals => {
  const { filterSelect } = this.state;
  const { form: { getFieldDecorator, getFieldValue }, filterList, } = this.props;

  getFieldDecorator('list', { initialValue: getFieldValue('list') || [{}], });

  const list = getFieldValue('list');

  // ...

  // 使用 list.map() 渲染筛选项表单项
  return (
    <Form>
      {/* ... */}
      {(list || []).map((item, index) => {
        return (
          // 筛选项表单项的代码
        );
      })}
    </Form>
  );
};
React Ant Design 筛选项表单组件:更新和新建功能实现

原文地址: https://www.cveoy.top/t/topic/qk7B 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录