解決Antd中Form表單的onChange事件中執(zhí)行setFieldsValue不生效
Antd中Form表單的onChange事件中執(zhí)行setFieldsValue不生效
如果在Form表單中onChange事件中,手寫了一個setFieldsValue, 則不會生效。
原因是因為
Form表單會在手寫的onChange事件之后執(zhí)行內(nèi)部的setFieldsValue,所以會將我們之前手寫的setFieldsValue給覆蓋掉。
解決方案
1. 使用setTimeout延時。此方案不推薦
2. 使用getValueFromEvent. 是當(dāng)onChange的時候,更改form表單的值的情景下使用
<FormItem label="路由節(jié)點" {...nodelayout}> ? ? ?{getFieldDecorator(`node`, { ? ? ? ? rules: [ ? ? ? ? ? ?{ ? ? ? ? ? ? ? required: true, ? ? ? ? ? ? ? message: '選擇要指定的路由節(jié)點', ? ? ? ? ? ? }], ? ? ? ? getValueFromEvent: (val: any) => { ? ? ? ? ? ? let nodesArr = [] as any; ? ? ? ? ? ? ?for (let item of transferList) { ? ? ? ? ? ? ? ? ?for (let j of val) { ? ? ? ? ? ? ? ? ? ? if ((item as any).id === j) { ? ? ? ? ? ? ? ? ? ? ? nodesArr.push(item); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ?} ? ? ? ? ? ? ?return nodesArr; ? ? ? ? } ? ? ?})( ? ? <Transfer ? ? ? ?operations={['>>', '<<']} ? ? ? ?dataSource={transferList} ? ? ? ?filterOption={(inputValue: any, option: any) => ? ? ? ? ? option.value.indexOf(inputValue) > -1 ? ? ? ?} ? ? ? ?showSearch ? ? ? ?lazy={false} ? ? ? ?targetKeys={targetKeys} ? ? ? ?onChange={transferHandleChange} ? ? ? ?onSearch={transferHandleSearch} ? ? ? ?render={item => item.value} ? ? />, )} </FormItem>
3. 如果你只想簡單的更改表單的值setFieldsValue,而不是在onChange的時候觸發(fā)。那么可以使用normalize. 與上述的getValueFromEvent類似,都是option的一個屬性。
antd Design Form setFieldsValue的使用
最近項目使用的是antd Design 4.x 版本,碰到個需要加載后端數(shù)據(jù)并展示,并且用戶可以進行修改的需求,前端采用的是antd的Form表單來實現(xiàn)
組件加載的時候向后端請求數(shù)據(jù)
componentDidMount() { ? ? ? ? gainCountry().then(res => { ?? ??? ??? ?// 這里進行數(shù)據(jù)請求 ?? ??? ??? ?...... ? ? ? ? }) ? ? }
form表單要回填數(shù)據(jù)一般會想到的是initialValues,但是這是適用于初始化值的時候,官方文檔的原話:“initialValues 不能被 setState 動態(tài)更新,你需要用 setFieldsValue 來更新”。
搜索一番setFieldsValue的使用,基本上都是:this.props.form.setFieldsValue, props自帶form,試用之后發(fā)現(xiàn)報錯,this.props下沒有form,這個好像只適用于antd 3.x
解決
antd4.x 中使用setFieldsValue 是通過ref來進行操作,如下所示:
class Index extends Component{ ?? ?constructor(props) { ? ? ? ? super(props) ? ? ? ? this.state = { } ? ? } ? ? // 創(chuàng)建一個ref ? ? formRef = React.createRef() ? ? render(){ ? ? ?? ?return{ ? ? ?? ? ? ? {/* 綁定到Form身上*/} ? ? ? ? ?? ? <Form ref={this.formRef}> ? ? ? ? ? ? ? ? <Form.Item name="example"> ? ? ? ? ? ? ? ? ? ?<Input /> ? ? ? ? ? ? ? ? </Form.Item> ? ? ? ? ? ? ?</Form> ? ? ? ? } ? ? } } export default BaseInfo
在需要的地方進行使用:
// example 為Form.Item中的name this.formRef.current.setFieldsValue({ ? ? ? ?example: ‘從后臺返回要顯示的值', ?? ??? ??? ??? ? })
結(jié)束語
官方文檔中都是有相關(guān)說明的,setFieldsValue 的使用我是在文檔中的一個例子中找到的,碰到問題的時候還是要多閱讀文檔
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue登錄頁實現(xiàn)使用cookie記住7天密碼功能的方法
這篇文章主要介紹了vue登錄頁實現(xiàn)使用cookie記住7天密碼功能的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02VUE + OPENLAYERS實現(xiàn)實時定位功能
本系列文章介紹一個簡單的實時定位示例,基于VUE + OPENLAYERS實現(xiàn)實時定位功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-09-09