0

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

(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 表格。以下是选择和取消选择功能:

(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”类,CSS 突出显示了这些行:

在此处输入图像描述

但是当我执行 unselect-all-rows 函数时,我只会得到一些未选择的行:

在此处输入图像描述

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

在此处输入图像描述

我在这里想念什么?

4

1 回答 1

1

当使用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..."]]))))

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

于 2020-08-06T17:58:12.537 回答