如何使用Reagent Hiccup在ClojureScript中添加点击事件以触发JavaScript事件

3

我刚开始使用Reagent,对Clojure很陌生。

我创建了一个移动菜单函数,并希望可以通过点击移动汉堡菜单来显示实际菜单。再次点击时,菜单必须隐藏。我不知道该怎么做。

(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")]]]]]])])

锚点需要展开和隐藏菜单。
   [: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时要执行什么操作?
(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
看起来你已经回答了你的主要问题。关于 .play 元素的部分之所以有效,是因为 'video' 是 https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play 的一个实例,所以该代码只是在 dom 元素上调用了这个内置方法。 - Justin L.
现在更有意义了,谢谢 :) - Clarice Bouwer
1个回答

3

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

(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-menure-frame/reg-event-db,该事件将切换菜单的可见性。

  • show_menu绑定订阅了re-frame/reg-sub :show-menu-mobile,从数据库获取:mobile-menu-visible值。

  • @show-menu值从数据库解构为真值,表示菜单应该隐藏或显示。


1
我喜欢这个解决方案。这是相当符合惯用法的 re-frame 代码。干得好! - Gary

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接