关于clojure:如何使用Reagent Hiccup添加click事件以触发ClojureScript中的JavaScript事件

How do I add a click event to trigger a JavaScript event in ClojureScript using Reagent Hiccup

我刚刚开始使用Reagent,对Clojure来说是个新手。

我已经创建了一个移动菜单功能,并希望可以单击移动汉堡菜单以显示实际菜单。再次单击时,菜单必须隐藏。我不知道该怎么办

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
(defn mobile-menu [primary-menu secondary-menu logo-el]
 [:div#ca-horizontal-mobile
  [:div#logo logo-el]
  [:div#menu-button
   [:a
    [:i.icon.bars]]]

  [:header#menu.mobile
   [:div
    [:div.center.menu
     (let [menu (concat primary-menu secondary-menu)]
       (for [i menu]
         [:div.item {:key (:key i)}
          [:a.item {:id   (:key i)
                    :href (:target i)} (:name i)]]))
     [:div.item
      [:a
       {:style    {:cursor :pointer}
        :id       :logout
        :on-click #(re-frame/dispatch [:logout])} (str"Logout")]]]]]])])

锚点需要展开并隐藏菜单。

1
2
   [:a
    [:i.icon.bars]]]

我所需要的只是一个如何在JavaScript事件上进行JavaScript调用的示例,以及一些帮助您理解它的帮助。

我在网上https://www.reddit.com/r/Clojure/comments/4ofct5/calling_methods_on_an_element_in_a_reagent/找到了此片段,但不确定如何将其连接起来。 .play元素如何知道on-click的操作?

1
2
3
4
5
(defn video-elem [src-url uid]
  [:div
    [:video {:src src-url :id uid}]
        [:button {:on-click #(.play (.getElementById js/document uid))}"Play!"]
        [:button {:on-click #(.pause (.getElementById js/document uid))}"Pause!"]])


在同事的帮助下,我们添加了以下内容。我不确定我是否正确解释了这一点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
(re-frame/reg-event-db
  :toggle-mobile-menu
  (fn [db _]
    (assoc db :mobile-menu-visible (not (:mobile-menu-visible db)))))

(re-frame/reg-sub :show-mobile-menu #(:mobile-menu-visible %))))

(defn mobile-menu [primary-menu secondary-menu logo-el]
  [:div#ca-horizontal-mobile
   [:div#logo logo-el]
   [:div#menu-button
    {:on-click #(re-frame/dispatch [:toggle-mobile-menu])}
    [:i.icon.bars]]

   (let [show-menu (re-frame/subscribe [:show-mobile-menu])]
     (if @show-menu
       [:header#menu.mobile
        [:div
         [:div.center.menu
          (let [menu (concat primary-menu secondary-menu)]
            (for [i menu]
              [:div.item {:key (:key i)}
               [:a.item {:id   (:key i)
                         :href (:target i)} (:name i)]]))
          [:div.item
           [:a
            {:style    {:cursor :pointer}
             :id       :logout
             :on-click #(re-frame/dispatch [:logout])} (str"Logout")]]]]]))])]])

  • 菜单按钮的单击事件调度:toggle-mobile-menu重新框架/ reg-event-db,从而切换菜单的可见性

  • show_menu绑定从db

    预订re-frame / reg-sub:show-menu-mobile which gets the:mobile-menu-visible`值

  • 数据库中的@show-menu值被解构为真实值,指示是否应隐藏或显示菜单。