【问题标题】:Antizer form submit data handlingAntizer表单提交数据处理
【发布时间】:2018-02-03 14:54:01
【问题描述】:

我想通过 antizer 在试剂中使用 ant design 组件,但我不知道如何在提交后从表单中提取字段值。我在documentation 中找不到任何内容。

比我更专业的人解决了这个问题?

【问题讨论】:

    标签: clojurescript reagent-forms


    【解决方案1】:

    如果您向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)])}])]
    

    希望这会有所帮助!

    【讨论】:

    • 我不明白我可以直接从每个字段中直接在 :on-change 事件中使用函数调用。非常感谢建议的实现,它确实有很大帮助!
    猜你喜欢
    • 2012-01-24
    • 1970-01-01
    • 2016-11-23
    • 2016-11-10
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多