Ant Design 表單中getFieldDecorator、getFieldValue、setFieldValue用法
1、getFieldDecorator
getFieldDecorator是一個方法,這個方法接收兩個參數,第一個是表單的字段對象,第二個是驗證規則。這個方法自己返回一個方法,須要將須要獲取值的標籤包裹進去。git
<From> <FormItem> //JS代碼書寫時須要用 { } 包裹起來,不能直接寫在代碼塊中 { getFieldDecorator('userName',{ initialValue:'Jack', rules:[] })( <Input placeholder='請輸入用戶名'/> ) } </FormItem> </From>
第一個參數是用戶自定義的、用於識別該控件的變量名,這樣便於在獲取或設置該控件的值。
2019.3.12補充:值得注意的是,getFieldDecorator是一個很是智能的方法,它能夠得到自定義組件的value值,在提交表單時會很方便。其次,initialValue的值會覆蓋子組件中的placeHolder,若是子組件是下拉框,也會根據initialValue的值來匹配本身的value,並顯示相應的值,能夠說很是智能了。
後端
2、getFieldValue
handleSubmit = e => { const { dispatch } = this.props; e.preventDefault(); var date_juban = this.props.form.getFieldValue('date_juban'); this.state.open_time_start = date_juban[0]; this.state.open_time_end = date_juban[1]; if (this.refs.pics.state.fileList.length > 0) this.state.image = this.refs.pics.state.fileList[0].response.url; this.state.location_longitude = this.props.form.getFieldValue('location_longitude'); this.state.location_latitude = this.props.form.getFieldValue('location_latitude'); }
在提交表單或是與後端交互時,若是須要一個控件的值,那麼就用this.props.form.getFieldValue('變量名')的方式進行獲取,注意:‘變量名’這個參數只能由getFieldDecorator所設定的。this
注意:getFieldValue不能獲取沒有使用getFieldDecorator綁定的控件(即:若是控件值標註了id屬性,用這個方法無效)。應使用document.getElementById("id名").value的方式進行獲取值。
3、setFieldValue
<FormItem {...formItemLayout} label={<span>地圖</span>}> <AMapModule lng={''} lat={''} address={getFieldValue('position')} getMapPoint={point => { setFieldsValue({ location_latitude: point.lat, location_longitude: point.lng, }); }} getMapAddress={address => { setFieldsValue({ position: address, }); }} /> </FormItem>
上述代碼是我在表單中截取的一部分,該控件是一個地圖控件。用戶點擊地圖中的某個位置,會在同頁面的input框中實時顯示經度、維度、位置描述。這三個input框的id分別是location_latitude、location_longitude、position。url