基礎的就是Ant Design的Form組件app
傳送門:https://ant.design/components/form-cn/ui
在最初的項目中,因爲我要用到Form,因此不得不把每一個帶表單的頁面(無論表單複雜與否)單獨放在一個JS文件中,而後就不得不涉及父子組件通訊方面的問題。this
基本結構是這樣的spa
1 class AddForm extends PureComponent{ 2 constructor(props){ 3 super(props); 4 ...... 5 } 6 7 ... 8 9 render(){ 10 const { getFieldDecorator } = this.props.form; 11 return( 12 <Form> 13 ... 14 </Form> 15 ) 16 } 17 } 18 19 const Add = Form.create()(AddForm); 20 export default Add;
表單提交時驗證&取值 (validateFields)code
1 let form = this.props.form; 2 form.validateFields((err, values) => { 3 if (!err) { 4 let obj = { 5 Name: values.Name, 6 ... 7 } 8 } 9 }
表單賦值 (setFieldsValue)component
1 let data = { 2 Name: 'xx', 3 Age: 33, 4 } 5 6 const { from } = this.props; 7 form.setFieldsValue({ 8 Name: data.Name, 9 Age: data.Age, 10 })
然後,我看了Ant Design Pro中的示例代碼,發現能夠在頁頭加入聲明orm
1 const myForm = Form.create()(props => { 2 const { form } = props; 3 4 return( 5 <FormItem label='姓名'> 6 {form.getFieldDecorator('Name',{ 7 rules: [{ required: true, message: 'x姓名不能爲空!' }], 8 })(<Input />)} 9 </FormItem> 10 ... 11 ) 12 } 13 14 //render調用 15 <myForm />
隨後衍生出來的問題就是,當我要在Modal中放入一個編輯表,必需要有初始化值blog
因而我查閱了API,Form.create(options),在create中提供多個參數ci
一看以後,經過 mapPropsToFields 就是能夠實現表單數據的映射,下面的完整的代碼get
1 const EditForm = Form.create({ 2 mapPropsToFields(props){ 3 if(props.data.Data!=undefined){ 4 const rxd = props.data.Data.RXD; 5 return { 6 RoadName:Form.createFormField({ value: rxd.RoadName }), 7 Position:Form.createFormField({ value: rxd.Position }), 8 } 9 } 10 11 } 12 })(props => { 13 const { form, modalVisible, handleModalVisible, handleAdd,data } = props; 14 const formItemLayout = { 15 labelCol: { span: 5 }, 16 wrapperCol: { span: 15 }, 17 }; 18 19 const okHandle = () => { 20 form.validateFields((err, fieldsValue) => { 21 if (err) return; 22 form.resetFields(); 23 //handleAdd(fieldsValue); 24 }); 25 }; 26 27 return ( 28 <Modal 29 destroyOnClose 30 title="編輯詳情" 31 visible={modalVisible} 32 onOk={okHandle} 33 onCancel={() => handleModalVisible()} 34 > 35 <FormItem {...formItemLayout} label="道路名稱"> 36 {form.getFieldDecorator('RoadName', { 37 rules: [{ required: true, message: '道路名稱不能爲空!' }], 38 })(<Input placeholder="請輸入" />)} 39 </FormItem> 40 <FormItem {...formItemLayout} label="詳細位置"> 41 {form.getFieldDecorator('Position')(<Input placeholder="請輸入" />)} 42 </FormItem> 43 <FormItem {...formItemLayout} label="長(m)"> 44 {form.getFieldDecorator('Long', { 45 rules: [ 46 { validator: decimalValidator, message: '小數點最多保留兩位!' }, 47 { required: false }, 48 ], 49 })(<InputNumber style={{ width: '100%' }} step={0.01} placeholder="請輸入" />)} 50 </FormItem> 51 <FormItem {...formItemLayout} label="完成日期"> 52 {form.getFieldDecorator('CompleteDate', { 53 rule: [{ required: true }], 54 })(<DatePicker style={{ width: '100%' }} />)} 55 </FormItem> 56 </Modal> 57 ); 58 59 });