还是拿代码来讲吧,详情见注释

子组件

  1. import React, { Component } from 'react';
  2. import { Form, Input } from 'antd';
  3. const FormItem = Form.Item;
  4. class Forms extends Component{
  5. getItemsValue = ()=>{ //3、自定义方法,用来传递数据(需要在父组件中调用获取数据)
  6. const valus= this.props.form.getFieldsValue(); //4、getFieldsValue:获取一组输入控件的值,如不传入参数,则获取全部组件的值
  7. return valus;
  8. }
  9. render(){
  10. const { form } = this.props;
  11. const { getFieldDecorator } = form; //1、将getFieldDecorator 解构出来,用于和表单进行双向绑定
  12. return(
  13. <>
  14. <Form layout="vertical">
  15. <FormItem label="姓名">
  16. {getFieldDecorator('name')( //2、getFieldDecorator 的使用方法,这种写法真的很蛋疼
  17. <Input />
  18. )}
  19. </FormItem>
  20. <FormItem label="年龄">
  21. {getFieldDecorator('age')(
  22. <Input />
  23. )}
  24. </FormItem>
  25. <FormItem label="城市">
  26. {getFieldDecorator('address')(
  27. <Input />
  28. )}
  29. </FormItem>
  30. </Form>
  31. </>
  32. )
  33. }
  34. }
  35. export default Form.create()(Forms); //创建form实例

getFieldDecorator 的具体参数见官方文档)

父组件

  1. import React, { Component } from 'react';
  2. import { Modal } from 'antd';
  3. import Forms from './Forms'
  4. export default class Modals extends Component {
  5. handleCancel = () => {
  6. this.props.closeModal(false);
  7. }
  8. handleCreate = () => {
  9. console.log(this.formRef.getItemsValue()); //6、调用子组件的自定义方法getItemsValue。注意:通过this.formRef 才能拿到数据
  10. this.props.getFormRef(this.formRef.getItemsValue());
  11. this.props.closeModal(false);
  12. }
  13. render() {
  14. const { visible } = this.props;
  15. return (
  16. <Modal
  17. visible={visible}
  18. title="新增"
  19. okText="保存"
  20. onCancel={this.handleCancel}
  21. onOk={this.handleCreate}
  22. >
  23. <Forms
  24. wrappedComponentRef={(form) => this.formRef = form} //5、使用wrappedComponentRef 拿到子组件传递过来的ref(官方写法)
  25. />
  26. </Modal>
  27. );
  28. }
  29. }

官方文档
  1. class CustomizedForm extends React.Component { ... }
  2. // use wrappedComponentRef
  3. const EnhancedForm = Form.create()(CustomizedForm);
  4. <EnhancedForm wrappedComponentRef={(form) => this.form = form} />
  5. this.form // => The instance of CustomizedForm