在作antd项目时发现,使用Form.create()(xxx)
建立的模块里面的Form
表单提交前能够使用this.props.form.validateFieldsAndScroll()
判断是否校验成功,this.props.form
也就是整个页面模块的Form
,那么,若是页面上有多个Form
,此时再使用this.props.form.validateFieldsAndScroll()
判断校验结果就是对整个页面的Form
进行判断,并不可以对单个Form
校验结果作判断,问题就在此,如何对单个Form
作判断?javascript
change
事件监听,获取表单元素值,手动作校验,这不失为一个方法,但有违react设计的思想。Form子组件:java
import React, { Component } from 'react';
import {Button, Form, Input, Select} from 'antd';
const FormItem = Form.Item;
class Forms extends Component{
getItemsValue = ()=>{
const val= this.props.form.getFieldsValue(); // 获取from表单的值
return val;
}
render(){
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const { form, initValue1, initValue2, initValueList } = this.props;
const { getFieldDecorator } = form; // 校验控件
return(
<Form style={{backgroundColor: '#fff', padding: '20px'}}> <FormItem {...formItemLayout} label={`相关数量`} > {getFieldDecorator(`amount`,{ rules: [{ message: '必填字段!', required: true }], initialValue: initValue1 ? initValue1 : undefined })( <Input placeholder="请输入"/> )} </FormItem> <FormItem {...formItemLayout} label={`选择相关名称`} > {getFieldDecorator(`name`,{ rules: [{ message: '必填字段!', required: false }], initialValue: initValue2 ? initValue2 : undefined })( <Select placeholder="请选择" onChange={this.handleSelectChange} > { initValueList && initValueList.map((x, i) => ( <Option value={x.Id} key={i}>{x.name}</Option> )) } </Select> )} </FormItem> </Form> ) } } export default Form.create()(Forms); //建立form实例 复制代码
Form子组件,接收父组件传过来的初始数据,组件中getItemsValue
自定义方法返回表单的值,须要在父组件中调用。react
父组件:antd
import React, { Component } from 'react';
import { Modal, Button } from 'antd';
import Forms from './Forms'
export default class Modals extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
initValue1: 0,
initValue2: 'myName',
initValueList: ["李云龙", "李荣基", "李达"]
};
}
handleClick = () => {
this.setState({
visible: true
})
};
handleCreate = () => {
let values = this.formRef.getItemsValue();
// 获取到子组件form的值,作进一步操做
this.setState({
visible: false
})
};
render() {
return (
<section> <Modal visible={this.state.visible} title="编辑" onOk={this.handleCreate} onCancel={() => { this.setState({ visible: false }); }} okText="保存" cancelText="取消" > <Forms initValue1={initValue1} initValue2={initValue2} initValueList={initValueList} wrappedComponentRef={(form) => this.formRef = form} /> </Modal> <Button onClick={()=>{ this.handleClick }}>点击弹框</Button> </section> ); } } 复制代码
这里关键的是使用wrappedComponentRef
属性拿到这个Form
的ref,简单的理解为拿到子组件的form实例,所以,能够在handleCreate
函数中经过this.formRef.getItemsValue()
调用自子组件的方法获取返回的form值。至此,上面的问题就解决了。app
关于wrappedComponentRef
的描述详见antd官网描述。函数