2017-08-25 39 views

回答

0

如果您提供對ant/validate-fields函數的回調,它將收到兩個參數:errorsvalues

如果輸入有效,則errors將爲null

第二個參數將始終包含當前表單數據。

;; Receive the output of `ant/validate-fields`, and react accordingly 
(defn submit-form-if-valid 
    [errors values] 
    (if (nil? errors) 
    (println "Form is valid."  values) 
    (println "Validation failed." errors))) 

(defn sample-form 
    (fn [props] 
    (let [my-form   (ant/create-form) 
      submit-handler #(ant/validate-fields my-form submit-form-if-valid)] 
     [:div 
     [ant/form {:on-submit #(do 
           (.preventDefault %) 
           (submit-handler))} 
     [ant/form-item ...] 
     [ant/form-item ...] 
     [ant/form-item ...] 
     [ant/form-item 
      [ant/button {:type "primary" 
         :html-type "submit"} 
      "Submit"]]]]))) 

注:就個人而言,我只能用這個功能來檢查errors。每次用戶更改字段時,我的表單數據都會連續記錄在app-db中。所以我的提交處理程序看起來更像這樣:

(defn submit-form-if-valid 
    [errors _] 
    (when (nil? errors) 
    (dispatch [:sample-form/submit!]))) 

我的重新框架事件看起來像這樣。一個事件來更新在DB中的表格數據(使用由形式輸入所提供的鍵/值對),和另一種實際提交表單:

(reg-event-db 
:sample-form/update-value 
[(path db/path)] 
(fn [db [_ k v]] 
    (assoc-in db [:sample-form-data k] v))) 

(reg-event-fx 
:sample-form/submit! 
[(path db/path)] 
(fn [{:keys [db]} _] 
    (let [form-data (:sample-form-data db)]) 
    ;; ... send data to back-end, handle the response, etc. 
)) 

並且每個我的形式輸入調用像這樣的事件:

[ant/form-item 
    (ant/decorate-field my-form "Thing #1" {:rules [{:required true}]} 
    [ant/input {:on-change #(dispatch [:sample-form/update-value :thing1 (-> % .-target .-value)])}])] 

希望這有助於!

+0

我不明白,我可以簡單地在每個字段直接使用函數調用:on-change事件。建議的實現非常感謝,它肯定有很大的幫助! –