输入文本试剂组件值格式

时间:2018-02-25 10:36:47

标签: text input format clojurescript reagent

我试图格式化输入的值" text"试剂成分没有成功。我希望在更改ratom变量的值之后,组件的值将在重新渲染时被格式化。 我使用cl-format格式化数字与空间千分隔符。我在第一次加载时效果很好,但在更改价格值后却没有。

保存新值后,是否可以格式化此示例的价格值?

(ns shopping.app
  (:require [reagent.core :as r]
            [cljs.pprint :refer [cl-format]]))

(defonce shoppinglist (r/atom (sorted-map
                           1 {:id 1 :name "Bread" :price 20},
                           2 {:id 2 :name "Milk" :price 12})))

(defn update-item! [fn & args]
  (apply swap! shoppinglist fn args))

(defn shopping-item [{:keys [id name price]} item]
  (let [rreadonly (r/atom true)
        rprice (r/atom price)]
      (fn [{:keys [id name price]} item]
      [:div
        [:label id]
        [:label (str " | " name)]
        [:input { :type "text"
                  :readOnly @rreadonly
                  :value (cl-format nil "~,,' :d" @rprice)
                  :on-change #(reset! rprice  (-> % .-target .-value))}]

        [:button {  :id "button-edit"
                    :hidden (not @rreadonly)
                    :on-click #(swap! rreadonly not)}
                    "Edit"]

        [:button {  :id "button-delete"
                    :hidden (not @rreadonly)
                    :on-click #(update-item! dissoc id)}
                    "Delete"]

        [:button {  :id "button-save"
                    :hidden @rreadonly
                    :on-click #(do 
                                  (update-item! assoc id (assoc {} :id id :name name :price (js/parseInt @rprice)))
                                  (swap! rreadonly not))}
                    "Save"]

        [:button {  :id "button-reset"
                    :hidden @rreadonly
                    :on-click #(do (reset! rprice price)
                                   (update-item! assoc id (assoc {} :id id :name name :price (js/parseInt @rprice)))
                                   (swap! rreadonly not))}
                    "Reset"]])))

(defn shopping-list []
  [:div.container
    (doall (for [item (vals @shoppinglist)]
      ^{:key (:id item)} [:div
        [shopping-item item]]))])

(defn init
  "Initialize components."
  []
  (let [container (.getElementById js/document "container")]
    (r/render-component 
      [shopping-list] 
      container)))

1 个答案:

答案 0 :(得分:0)

这不起作用,因为您正在创建一个循环:

  • on-changerprice原子的值设置为字符串,但在此表达式中(cl-format nil "~,,' :d" @rprice) @rprice应为数字
  • 当您将输入的value设置为某个格式化值时,下次键入内容时on-change将看到此格式化的值而不是之前的原始输入,那么rprice的内容{1}}将设置为格式化值,即字符串

因此,如果您将rstring设置为原始数字或格式化字符串,则在一个周期后,它将始终为格式化字符串。

不幸的是,在输入时格式化输入有点复杂,您可能需要一个库。也许试剂形式支持它:https://github.com/reagent-project/reagent-forms,如果没有,还有其他的React库。