我正在使用 clojurescript 和试剂开发一个简单的网络应用程序。我想创建一个简单的“选项卡”组件,其中将包含(对于初学者来说)一个文本输入组件。
该应用有 2 个选项卡,用户可以选择一个选项卡,我想“保留”这两个选项卡中的值。
代码如下:
(defn atom-input [value]
[:input {:type "text"
:value @value
:on-change #(reset! value (-> % .-target .-value))}])
(defn simple-tab [index]
(let [pg-index (atom 1)
a (atom 0)]
(fn []
[:div
[:h4 (str "index: " @index)]
[atom-input a]])))
(defn main-page []
(let [index (atom 0)]
[:div.container
[:div.row
[:button {:on-click (fn [] (reset! index 0))} "select tab 1"]
[:button {:on-click (fn [] (reset! index 1))} "select tab 2"]]
[:div.row
[simple-tab index]]]))
(defn ^:export run []
(reagent/render-component
(fn [] [main-page])
(.-body js/document)))
问题是,当我切换选项卡时,组件共享输入字段的值 - 我在这里做错了什么?
非常感谢您的帮助!
最佳答案
问题是您将 a (atom 0)
传递给 atom-input
控件:[atom-input a]
。
这导致您的选项卡之间共享相同的原子值。
如果您不想共享该值,则需要将 a
更改为映射:a (atom {})
并传递映射和atom-input
的索引,例如:
(defn atom-input [value index]
[:input {:type "text"
:value (or (get @value index) "")
:on-change #(swap! value assoc index (-> % .-target .-value))}])
(defn simple-tab [index]
(let [pg-index (atom 1)
a (atom {})]
(fn []
[:div
[:h4 (str "index: " @index)]
[atom-input a @index]])))
恕我直言,更好的方法是使用光标,这样您就不需要将索引和整个映射传递给atom-input
,例如:
(defn atom-input [value]
[:input {:type "text"
:value (or @value "")
:on-change #(reset! value (-> % .-target .-value))}])
(defn simple-tab [index]
(let [pg-index (atom 1)
a (atom {})]
(fn []
[:div
[:h4 (str "index: " @index)]
[atom-input (reagent/cursor [@index] a)]])))
关于Clojurescript + 试剂问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27779315/