Ant Design 表單中getFieldDecorator、getFieldValue、setFieldValue用法
一、getFieldDecorator
getFieldDecorator是一個方法,這個方法接收兩個參數,第一個是表單的字段對象,第二個是驗證規則。這個方法本身返回一個方法,需要將需要獲取值的標簽包裹進去。
<From>
<FormItem>
//JS代碼書寫時需要用 { } 包裹起來,不能直接寫在代碼塊中
{
getFieldDecorator('userName',{
initialValue:'Jack',
rules:[]
})(
<Input placeholder='請輸入用戶名'/>
)
}
</FormItem>
</From>
第一個參數是用戶自定義的、用於識別該控件的變量名,這樣便於在獲取或設置該控件的值。
2019.3.12補充:值得注意的是,getFieldDecorator是一個非常智能的方法,它可以獲得自定義組件的value值,在提交表單時會很方便。其次,initialValue的值會覆蓋子組件中的placeHolder,如果子組件是下拉框,也會根據initialValue的值來匹配自己的value,並顯示相應的值,可以說非常智能了。
二、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所設定的。
注意:getFieldValue不能獲取沒有使用getFieldDecorator綁定的控件(即:如果控件值標注了id屬性,用這個方法無效)。應使用document.getElementById("id名").value的方式進行獲取值。
三、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。
