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, // }); const { form } = this.props; const list = form.getFieldValue('list') || []; const nextList = [...list, {}]; 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; ;

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)} </> ); } }

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

export default UpdateForm; // 添加 add = () => { // const { form } = this.props; // const list = form.getFieldValue('list'); // const nextList = list?.concat({}); // form.setFieldsValue({ // list: nextList, // }); const { form } = this.props; const list = form.getFieldValue('list') || []; const nextList = [...list, {}]; form.setFieldsValue({ list: nextList, }); }这个方法新增不了内容:该方法是用于在表单中添加一个新的筛选类项。在点击“新增”按钮时,会调用该方法,将一个空对象添加到表单的list字段中。然后在renderContent方法中遍历list字段的每个元素,生成对应的表单项。

可能的原因是在表单中没有正确获取到list字段的值。可以尝试在add方法中打印出list的值,检查是否正确获取到。如果没有正确获取到list的值,可以检查表单的getFieldValue方法是否正确使用。

React 筛选条件表单组件 - 更新和新增筛选项

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

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