1. 程式人生 > >antd 父組件獲取子組件中form表單的值

antd 父組件獲取子組件中form表單的值

文檔 port lock xtend ret pro cor design code

還是拿代碼來講吧,詳情見註釋

子組件

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class Forms extends Component{
    getItemsValue = ()=>{    //3、自定義方法,用來傳遞數據(需要在父組件中調用獲取數據)
        const valus= this.props.form.getFieldsValue();       //4、getFieldsValue:獲取一組輸入控件的值,如不傳入參數,則獲取全部組件的值
        return valus;
    }
    render(){
        const { form } = this.props;
        const { getFieldDecorator } = form;    //1、將getFieldDecorator 解構出來,用於和表單進行雙向綁定
        return(
            <>
                <Form layout="vertical">
                    <FormItem label="姓名">
                        {getFieldDecorator('name')(    //2、getFieldDecorator 的使用方法,這種寫法真的很蛋疼
                            <Input />
                        )}
                    </FormItem>
                    <FormItem label="年齡">
                        {getFieldDecorator('age')(
                            <Input />
                        )}
                    </FormItem>
                    <FormItem label="城市">
                        {getFieldDecorator('address')(
                            <Input />
                        )}
                    </FormItem>
                </Form>
            </>
        )
    }
}

export default Form.create()(Forms);        //創建form實例

getFieldDecorator 的具體參數見官方文檔

父組件

import React, { Component } from 'react';
import { Modal } from 'antd';
import Forms from './Forms'

export default class Modals extends Component {
    handleCancel = () => {
        this.props.closeModal(false);
    }
    handleCreate = () => {
        console.log(this.formRef.getItemsValue());     //6、調用子組件的自定義方法getItemsValue。註意:通過this.formRef 才能拿到數據
        this.props.getFormRef(this.formRef.getItemsValue());
        this.props.closeModal(false);
    }
    render() {
        const { visible } = this.props;
        return (
            <Modal
                visible={visible}
                title="新增"
                okText="保存"
                onCancel={this.handleCancel}
                onOk={this.handleCreate}
            >
            <Forms
                wrappedComponentRef={(form) => this.formRef = form}       //5、使用wrappedComponentRef 拿到子組件傳遞過來的ref(官方寫法)
            />
            </Modal>
        );
    }
}
官方文檔
class CustomizedForm extends React.Component { ... }

// use wrappedComponentRef
const EnhancedForm = Form.create()(CustomizedForm);
<EnhancedForm wrappedComponentRef={(form) => this.form = form} />
this.form // => The instance of CustomizedForm

antd 父組件獲取子組件中form表單的值