0

我有一个嵌套的动态表单。

目前,如果我在城市字段中输入一些内容,然后在州字段中输入两个字母,然后在下一个字段中输入两个字母,州字段不会保持填充状态。我希望它与我的州保持一致。非常简单的常见行为。示例截图:

前

一旦我切换到下一个字段,State 就会返回空白:

后

我相信基本上做到这一点的方法是在用户退出时使用 Select 元素的 onblur 选项来填充它。事实上,当它不是这里的嵌套组件时,我曾经让它工作。不幸的是,当我重构它以使其嵌套时,我破坏了它。我认为我的 ref 坏了,我不知道如何使用 forwardref 来修复它,但我可能会离开这里。裁判有点让我头晕目眩。

希望那里有善良的灵魂可以帮助我了解如何解决它。我现在也收到警告,列表中的每个孩子都应该有一个唯一的“关键”道具,我不确定为什么。

父组件 TenantForm.js

import React from "react";
import moment from "moment";
import { Form, Input, Select } from "antd";
import ArrayOfSubFormComponentsForApplicants from "./ArrayOfSubFormComponentsForApplicants";

const rules = [{ required: true }];

const validateMessages = {
  required: "Required!",
  types: {
    email: "Invalid E-mail!",
    number: "Invalid Number!",
  },
  number: {
    range: "Must be between ${min} and ${max}",
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 36, offset: 0 },
    sm: { span: 16, offset: 6 },
  },
};

export default class TenantForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      tenant: {
        applicants: [
          {
            firstName: props.tenant ? props.tenant.first : "",
            middleName: props.tenant ? props.tenant.middle : "",
            lastName: props.tenant ? props.tenant.last : "",
            street: props.tenant ? props.tenant.street : "",
            city: props.tenant ? props.tenant.city : "",
            state: props.tenant ? props.tenant.state : "",
            zipcode: props.tenant ? props.tenant.zipcode : "",
          },
        ],
        error: "",
      }
    };
  }  
    
  handleFieldChange = (field) => (event, value, selectedKey) => {
    // make a copy of the object first to avoid changes by reference
    let data = { ...this.state.data };  
  
    // use here event or value of selectedKey depending on your component's event
    data[field] = value;  
  
    this.setState({ data });
  }

  render() {
    const onFinish = (values) => {
      console.log("onFinish: ", values);
      this.props.onSubmit({
        applicants: values.applicants,
      });
    };
    return (
      <Form
        {...formItemLayoutWithOutLabel}
        onFinish={onFinish}
        id="myForm"
        validateMessages={validateMessages}
        initialValues={{ applicants: [{ firstName: "" }] }}
      >
        <ArrayOfSubFormComponentsForApplicants
          value={this.state.tenant.applicants}
          onChange={this.handleFieldChange('applicants')}
        />
      </Form>
    );
  }
}

子组件 ArrayOfSubFormComponentsForApplicants.js

import React from "react";
import SubFormComponentForApplicants from './SubFormComponentForApplicants';

export default class ArrayOfSubFormComponentsForApplicants extends React.Component {
  
  handleFieldChange = (index) => (event, value, selectedKey) => {
    let data = [...this.props.value];
    data[index] = value;
    this.props.onChange(null, data);
  }

  render() {
    return (
      <div>
        {this.props.value.map((subform, index) =>
          <SubFormComponentForApplicants
            key={subform.key}
            value={subform}
            onChange={this.handleFieldChange(index)}
          />
        )}
      </div>
    )
  }
}

export default ArrayOfSubFormComponentsForApplicants

子组件 SubFormComponentForApplicants.js

import React from "react";
import moment from "moment";
import { Form, Input, Col, Row, Select, Button, DatePicker, Switch } from "antd";
import { PlusOutlined, DeleteTwoTone } from "@ant-design/icons";

const InputGroup = Input.Group;
const Option = Select.Option;
const { TextArea } = Input;
const maxApplicants = 4;

const rules = [{ required: true }];

const STATES = [
  "AL",
  "AK",
  "AZ",
  "AR",
  "CA",
  "CO",
  "CT",
  "DE",
  "DC",
  "FM",
  "FL",
  "GA",
  "GU",
  "HI",
  "ID",
  "IL",
  "IN",
  "IA",
  "KS",
  "KY",
  "LA",
  "ME",
  "MH",
  "MD",
  "MA",
  "MI",
  "MN",
  "MS",
  "MO",
  "MT",
  "NE",
  "NV",
  "NH",
  "NJ",
  "NM",
  "NY",
  "NC",
  "ND",
  "MP",
  "OH",
  "OK",
  "OR",
  "PW",
  "PA",
  "PR",
  "RI",
  "SC",
  "SD",
  "TN",
  "TX",
  "UT",
  "VT",
  "VI",
  "VA",
  "WA",
  "WV",
  "WI",
  "WY",
];

const validateMessages = {
  required: "Required!",
  types: {
    email: "Invalid E-mail!",
    number: "Invalid Number!",
  },
  number: {
    range: "Must be between ${min} and ${max}",
  },
};

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 36 },
    sm: { span: 16 },
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 36, offset: 0 },
    sm: { span: 16, offset: 6 },
  },
};

class SubFormComponentForApplicants extends React.Component {
  
  constructor(props) {
    super(props);

    this.state = {
      applicants: [
        {
          firstName: props.tenant ? props.tenant.first : "",
          middleName: props.tenant ? props.tenant.middle : "",
          lastName: props.tenant ? props.tenant.last : "",
          street: props.tenant ? props.tenant.street : "",
          city: props.tenant ? props.tenant.city : "",
          state: props.tenant ? props.tenant.state : "",
          zipcode: props.tenant ? props.tenant.zipcode : "",
        },
      ],
      error: "",
    };
  }

  render() {
    return (
          <Form.List name="applicants">
            {(fields, { add, remove }) => {
              return (
                <div>
                  {fields.map((field, index) => (
                    <Form.Item {...formItemLayout} label={`Applicant #${index + 1}`} key={field.key}>
                      <Row key={field.key} gutter={[0, 8]} justify="start">
                        <Col>
                          <Row gutter={[4, 4]}>
                            <Col span={7}>
                              <Form.Item name={[field.name, "firstName"]} fieldKey={[field.fieldKey, "firstName"]} rules={rules}>
                                <Input placeholder="First Name" />
                              </Form.Item>
                            </Col>
                            <Col span={7}>
                              <Form.Item name={[field.name, "middleName"]} fieldKey={[field.fieldKey, "middleName"]} initialValue="">
                                <Input placeholder="Middle Name" />
                              </Form.Item>
                            </Col>
                            <Col span={9}>
                              <Form.Item name={[field.name, "lastName"]} fieldKey={[field.fieldKey, "lastName"]} rules={rules}>
                                <Input placeholder="Last Name" />
                              </Form.Item>
                            </Col>
                            <Col flex="none">
                              {index > 0 ? (
                                <DeleteTwoTone
                                  className="dynamic-delete-button"
                                  onClick={() => {
                                    remove(field.name);
                                  }}
                                />
                              ) : null}
                            </Col>
                          </Row>
                          <Row gutter={[4, 4]}>
                            <Col span={23}>
                              <Form.Item name={[field.name, "address"]} fieldKey={[field.fieldKey, "address"]} rules={rules}>
                                <Input placeholder="Address" />
                              </Form.Item>
                            </Col>
                          </Row>
                          <Row gutter={[4, 4]}>
                            <Col span={12}>
                              <Form.Item name={[field.name, "city"]} fieldKey={[field.fieldKey, "city"]} rules={rules}>
                                <Input placeholder="City" />
                              </Form.Item>
                            </Col>
                            <Col span={5}>
                              <Form.Item name={[field.name, "state"]} fieldKey={[field.fieldKey, "state"]} rules={rules}>
                                <Select
                                  showSearch
                                  placeholder="State"
                                  defaultActiveFirstOption={true}
                                >
                                  {STATES.map((state) => (
                                    <Option value={state} key={state}>
                                      {state}
                                    </Option>
                                  ))}
                                </Select>
                              </Form.Item>
                            </Col>
                            <Col span={6}>
                              <Form.Item name={[field.name, "zipcode"]} fieldKey={[field.fieldKey, "zipcode"]} rules={rules}>
                                <Input placeholder="Zip Code" />
                              </Form.Item>
                            </Col>
                          </Row>
                        </Col>
                      </Row>
                    </Form.Item>
                  ))}
                  <Form.Item>
                    {fields.length < maxApplicants ? (
                      <Button
                        type="dashed"
                        onClick={() => {
                          add();
                        }}
                        style={{ width: "100%" }}
                      >
                        <PlusOutlined /> Add Applicant
                      </Button>
                    ) : null}
                  </Form.Item>
                </div>
              );
            }}
          </Form.List>
    );
  }
}

export default SubFormComponentForApplicants;
4

0 回答 0