antd页面多表单校验
生活随笔
收集整理的這篇文章主要介紹了
antd页面多表单校验
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題
在做antd項目時發現,使用Form.create()(xxx)創建的模塊里面的Form表單提交前可以使用this.props.form.validateFieldsAndScroll()判斷是否校驗成功,this.props.form也就是整個頁面模塊的Form,那么,如果頁面上有多個Form,此時再使用this.props.form.validateFieldsAndScroll()判斷校驗結果就是對整個頁面的Form進行判斷,并不能夠對單個Form校驗結果做判斷,問題就在此,如何對單個Form做判斷?
解決方法
案例實現
Form子組件:
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})(<Selectplaceholder="請選擇"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自定義方法返回表單的值,需要在父組件中調用。
父組件:
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><Modalvisible={this.state.visible}title="編輯"onOk={this.handleCreate}onCancel={() => {this.setState({ visible: false });}}okText="保存"cancelText="取消"><FormsinitValue1={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值。至此,上面的問題就解決了。
關于wrappedComponentRef的描述詳見antd官網描述。
轉載于:https://juejin.im/post/5cad6567e51d456e5a0728b3
總結
以上是生活随笔為你收集整理的antd页面多表单校验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IoT原型开发利用现成的单板设计---凯
- 下一篇: 三星S6D1121主控彩屏(240*32