2017-08-25 40 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事件。建议的实现非常感谢,它肯定有很大的帮助! –