更改 class 字符串时 Clojurescript 应用程序出现问题

Issue in Clojurescript application when changing class strings

我的应用程序中有一些 Clojurescript 出现奇怪的问题。我将所有相关部分拉出到一个小的 Leiningen 试剂应用程序中。这是相关的打嗝:

(defn current-page []
  (fn []
    (let [page (:current-page (session/get :route))]
      [:div
      [:table {:width "100%"}
        [:tbody
          [:tr {:class "row"}
            [:td "A"] [:td "B"] [:td "C"]]
          [:tr {:class "row"}
            [:td "A"] [:td "B"] [:td "C"]]
          [:tr {:class "row"}
            [:td "A"] [:td "B"] [:td "C"]]
          [:tr {:class "row"}
            [:td "A"] [:td "B"] [:td "C"]]
          [:tr {:class "row"}
            [:td "A"] [:td "B"] [:td "C"]]
          [:tr {:class "row"}
            [:td "A"] [:td "B"] [:td "C"]]                                                            
          [:tr {:class "row"}
            [:td "A"] [:td "B"] [:td "C"]]]]
      [:div {:onClick #(unselect-all-rows)} "Unselect All Rows..."]       
      [:div {:onClick #(select-all-rows)} "Select All Rows..."] ])))

这只是一个简单的 HTML table。下面是 select 和 unselect 函数:

(defn unselect-all-rows []
  (prn "Unselecting all.")
  (let [selected-rows (.getElementsByClassName js/document "row-selected")]
    (prn (str "Rows selected: " (.-length selected-rows)))
    (doall (map #(.remove (.-classList %) "row-selected") (array-seq selected-rows)))))

(defn select-all-rows []
  (prn "Selecting all.")
  (let [selectable-rows (.getElementsByClassName js/document "row")]
    (doall (map #(.add (.-classList %) "row-selected") (array-seq selectable-rows))))) 

select-all-rows 函数按预期工作,所有行都应用“row-selected”class,CSS 突出显示行:

但是当我执行 unselect-all-rows 函数时,我只得到一些行 unselected:

如果我再单击 2 次,则所有行最终都未selected。如果我查看控制台,selected 的行数是我所期望的,在第​​一种情况下为 7,但它似乎只对交替行执行删除操作:

我在这里错过了什么?

当使用 reagent 或任何其他类型的 react 包装器时,您的视图函数是唯一应该修改 DOM 的东西。你自己不做任何直接的 DOM 操作。因此,您可以在某处捕获所选行的状态(本地原子或某种其他类型的托管状态,例如 re-frame)。

所以一个简单的版本可能是这样的:

(defn current-page []
  (let [toggle-ref (r/atom false)
        select-all #(reset! toggle-ref true)
        deselect-all #(reset! toggle-ref false)]
    (fn []
      (let [page (:current-page (session/get :route))
            row-class (if @toggle-ref "row-selected" "row")]
        [:div
         [:table {:width "100%"}
          [:tbody
           [:tr {:class row-class}
            [:td "A"] [:td "B"] [:td "C"]]
           [:tr {:class row-class}
            [:td "A"] [:td "B"] [:td "C"]]
           [:tr {:class row-class}
            [:td "A"] [:td "B"] [:td "C"]]
           [:tr {:class row-class}
            [:td "A"] [:td "B"] [:td "C"]]
           [:tr {:class row-class}
            [:td "A"] [:td "B"] [:td "C"]]
           [:tr {:class row-class}
            [:td "A"] [:td "B"] [:td "C"]]
           [:tr {:class row-class}
            [:td "A"] [:td "B"] [:td "C"]]]]
         [:div {:onClick deselect-all} "Unselect All Rows..."]
         [:div {:onClick select-all} "Select All Rows..."]]))))

我实际上并没有测试这段代码,实际上您可能想存储实际选择了哪些行,但它应该让您了解这是如何工作的。