使用父组件中的“提交”按钮更新用户表单

时间:2019-07-18 09:04:04

标签: javascript reactjs ecmascript-6 redux react-redux

我有一个父组件“ UserForm”,正在使用Ant设计的“步骤”模块,并且正在调用多个患者表格PatientForm,PatientForm2 ...

但是“下一步”和“提交”按钮在父组件中,当我单击“下一步”或“从步骤标题更改”时,我想要更新患者。

UserForm.js:

import React from "react";
import "antd/dist/antd.css";
import { Steps, Button, message, Form } from "antd";
import PatientForm from "./PatientForm.js";
import PatientForm2 from "./PatientForm2.js";
import PatientForm3 from "./PatientForm3.js";
import PatientForm4 from "./PatientForm4.js";
import PatientForm5 from "./PatientForm5.js";
import PatientForm6 from "./PatientForm6.js";
import Success from "./Success";
import { connect } from "react-redux";
const { Step } = Steps;



class UserForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      current: 0
    };
  }

  async componentDidMount() {
    const { id } = this.props.match.params;
    console.log("DidMOunt - patientId", id);

      const params = { id, complete: true };
      const { success, data } = await fetchPrivateSingle("patient", params);

    if (this.props.reduxPatient && this.props.reduxPatient._id) {
      console.log(this.props.reduxPatient);
    } else {
      console.log(id);
    }
  }

  onChange = current => {
    this.setState({ current });
  };



  prev() {
    const current = this.state.current - 1;
    this.setState({ current });
  }

  render() {

    const steps = [
      {
        title: "step1",
        content: <PatientForm patient={this.props.reduxPatient}></PatientForm>,
        id: 1
      },
      {
        title: "step2",
        content: <PatientForm2></PatientForm2>,
        id: 2
      },
      {
        title: "step3",
        content: <PatientForm3></PatientForm3>,
        id: 3
      },
      {
        title: "step4",
        content: <PatientForm4></PatientForm4>,
        id: 4
      },
      {
        title: "step5",
        content: <PatientForm5></PatientForm5>,
        id: 5
      },
      {
        title: "step6",
        content: <PatientForm6></PatientForm6>,
        id: 6
      },
      {
        title: "Confirmation",
        content: <Success></Success>,
        id: 7
      }
    ];

   const { current } = this.state;

    const next = () => {
      const current = this.state.current + 1;
      this.setState({ current });
    }

    return (
      <div>
        <Steps current={current} onChange={this.onChange}>
          {steps.map(item => (
            <Step key={item.title} title={item.title} />
          ))}
        </Steps>
        <div className="steps-content">
          {steps[current].content}
        </div>
        <div className="steps-action">
          {current < steps.length - 1 && (
            <Button type="primary" onClick={() => next()}>
              Suivant
            </Button>
          )}
          {current === steps.length - 1 && (
            <Button
              type="primary"
              onClick={() => message.success("Processing complete!")}
            >
              Confirmer
            </Button>
          )}
          {current > 0 && (
            <Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>
              Retourner
            </Button>
          )}
        </div>
      </div>
    );
  }
}
const mapStateToProps = state => ({
  reduxPatient: state.patientFormState.patient
});

const WrappedPatientForm = Form.create()(UserForm);
export default connect(mapStateToProps)(WrappedPatientForm);

PatientForm.js:

import React, { Component } from 'react';
import PropTypes from "prop-types";
import LinearIcon from "components/LinearIcon";
import { Form, Input, Button, DatePicker, Radio, Upload, message, Icon, Select} from "antd";
import { geocodeByAddress, getLatLng } from "react-places-autocomplete";
import moment from 'moment';
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

class PatientForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      current: 0,
      loaded: false,
      patients: [],
      address: '',
      valueRadio: 1,
      adr: ''
    };  
  }

  continue = e => {
    e.preventDefault();
    this.props.nextStep();
  };

  onChange = e => {
    this.setState({
      valueRadio: e.target.value,
    });
  };

  handleSelect = (address) => {
    geocodeByAddress(address)
      .then(results => getLatLng(results[0]))
  }

  checkFirstLast = (rule, value, callback) => {
    if (value && (value.length < 2 || value==="" )) {
      callback('');
    } else {
      callback();
    }
  }

  checkPhoneNumber = (rule, value, callback) => {
    if (value && (value.length < 10 || value==="" || isNaN(value))){
      callback('');
    } else {
      callback();
    }
  }

  async componentDidMount() {

    var firstname = this.props.patient.firstname;
    var Curruentlastname = this.props.patient.lastname;
    const { setFieldsValue } = this.props.form;
    const setValues = {
      firstname,
      Curruentlastname
    };

    setFieldsValue(setValues);
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const props = {
      name: 'file',
      action: '',
      headers: {
        authorization: 'authorization-text',
      },
      onChange(info) {
        if (info.file.status !== 'uploading') {
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} Succes`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} Fail`);
        }
      },
    };

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };

      return (

<div>

      <div className="grid">
      <div className="grid__content">
        <div className="card account__content__desktop">

      <React.Fragment>
        <div className="card__title">
          <LinearIcon className="card__title__icon" name="user" />
          Step 1 
        </div>
        <Form {...formItemLayout}> 


        <FormItem label="Civilité"  required="true">
        <Radio.Group onChange={this.onChange} value={this.state.valueRadio} >
        <Radio value={1}>Monsieur</Radio>
        <Radio value={2}>Madame</Radio>
      </Radio.Group>
      </FormItem>

      <FormItem label="Nom de naissance" hasFeedback  required="true">
          {getFieldDecorator("Originlastname", {
            rules: [
              {
                validator: this.checkFirstLast
              }
            ]
          })(<Input icon="user" placeholder="Nom de naissance"  required="true" />)}
        </FormItem>

      <FormItem label="Nom usuel" hasFeedback required="true">
          {getFieldDecorator("Curruentlastname", {
            rules: [
              {
                validator: this.checkFirstLast
              }
            ]
          })(<Input icon="user" placeholder="Nom usuel " prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}/>)}
        </FormItem>

      <FormItem label="Prénom" hasFeedback   required="true">
      {getFieldDecorator('firstname', {
            rules: [ {
              validator: this.checkFirstLast
            }],
          })(<Input icon="user" placeholder="Prénom" />)}
        </FormItem>





        <FormItem label="Date de naissance"  required="true">
          <DatePicker style={{ width: '100%',zIndex: '1' }} defaultValue={moment(this.props.patient.birthdate, 'YYYY-MM-DD')}/>
        </FormItem>

        <FormItem label="Lieu de naissance" hasFeedback  required="true">
      {getFieldDecorator('PlaceofBirth', {
            rules: [ {
              validator: this.checkFirstLast
            }],
          })(<Input icon="user" placeholder="Lieu de naissance"  suffix={<Icon type="close-circle" style={{ color: 'rgba(0,0,0,.25)' }} />}/>)}
        </FormItem>

        <Form.Item label="Pièce d'identité"  required="true">
          {getFieldDecorator('CIN', {
          })(<Input.Group compact>
             <Select defaultValue="CIN" style={{ width: '80%' }}>
            <Option value="CIN">Carte Nationale D'identité</Option>
            <Option value="CS">Carte de séjour</Option>
            <Option value="passeport">Passeport</Option>
          </Select>
          <Upload {...props}>
            <Button>
              <Icon type="upload" /> Cliquez ici pour télécharger
            </Button>
          </Upload>
          <RangePicker 
      showTime={{ format: 'HH:mm' }}
      format="YYYY-MM-DD HH:mm"
      placeholder={['Date début', 'Date fin']}
    />
          </Input.Group>
          )}
        </Form.Item>


        </Form>
      </React.Fragment>
      </div>
      </div>
    </div>
    </div>

    );  
  }
}

PatientForm.proptypes = {
  user: PropTypes.object.isRequired
};

const WrappedPatientForm = Form.create()(PatientForm);
export default WrappedPatientForm;

请帮忙吗?

0 个答案:

没有答案