??在react開(kāi)發(fā)過(guò)程中,難免會(huì)遇到在父組件中獲取子組件中的值崖飘,如在創(chuàng)建一個(gè)對(duì)話(huà)框提交表單的時(shí)候,我們應(yīng)該怎么來(lái)實(shí)現(xiàn)通過(guò)點(diǎn)擊antd 中modal組件的確定按鈕獲取表單的值去發(fā)送AJAX,下面直接上代碼:
子組件:
import React, { Component } from "react";
import { Form, Input } from 'antd';
class BaseForm extends Component {
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form {...formItemLayout} onSubmit={this.handleSubmit}>
<Form.Item label="設(shè)備名稱(chēng)">
{getFieldDecorator("equipmentName")(<Input />)}
</Form.Item>
<Form.Item label="設(shè)備類(lèi)型">
{getFieldDecorator("type")(<Input />)}
</Form.Item>
<Form.Item label="設(shè)備測(cè)試">
{getFieldDecorator("test")(<Input />)}
</Form.Item>
</Form>
);
}
}
export default Form.create()(BaseForm)
父組件:
import React, { Component } from "react";
import { Modal } from "antd";
import BaseForm from "./components/baseForm";
class componentName extends Component {
state = {
visible: false
};
render() {
const { visible } = this.state;
return (
<div>
<Modal
bodyStyle={{ maxHeight: "500px", overflowY: "scroll" }}
title="title"
visible={visible}
onOk={this.handleOk}
onCancel={() => this.setState({ visible: false })}
>
<BaseForm wrappedComponentRef={this.saveFormRef} />
</Modal>
</div>
);
}
// 通過(guò)wrappedComponentRef獲取子組件的ref
saveFormRef = formRef => {
this.formRef = formRef;
};
handleOk = () => {
const form = this.formRef.props.form;
form.validateFields((err, fieldsValue) => {
if (!err) {
console.log(fieldsValue);
}
});
};
}
export default componentName;
總結(jié): 通過(guò)antd官方文檔給出的wrappedComponentRef去綁定子組件的ref實(shí)現(xiàn)父組件獲取子組件表單值参歹,至此强挫,我們就可以獲取到我組件中的值了岔霸,當(dāng)然我們也可以把form表單和Modal對(duì)話(huà)框都封裝成一個(gè)通用的組件,使用起來(lái)會(huì)更加的方便俯渤。