使用Om有条件地将一个类添加到元素

时间:2015-01-15 21:45:00

标签: reactjs clojurescript om

在Om中,有没有办法根据主app atom中的某个值为元素添加一个类?

采取以下元素,例如:

(defn some-component [app owner]
  (reify
    om/IRender
    (render
      [_]
      (html
        [:div {:class (when (:some-key app) "awesomeclass")} "Some text!"])))) 

如果我以某种方式将:some-key的值在true和false之间切换,则该类不会被添加或删除。页面加载时:some-key的值决定了是否添加了类。

我正在使用这个想法根据我的app状态中hide键的值有条件地显示/隐藏(使用Twitter Bootstrap' :access类)菜单选项:

[:ul.dropdown-menu {:role "menu"}
  [:li {:class (when (:access app) "hide")} [:a.pointer {:on-click #(om/update! app :view :login)} "Login"]]
  [:li {:class (when (:access app) "hide")} [:a.pointer {:on-click #(om/update! app :view :register)} "Register"]]
  [:li {:class (when-not (:access app) "hide")} [:a.pointer {:on-click #(om/update! app :view :dashboard)} "Dashboard"]]
  [:li {:class (when-not (:access app) "hide")} [:a.pointer {:on-click #(om/update! app :view :settings)} "Settings"]]
  [:li [:a.pointer {:on-click #(om/update! app :view :about)} "About"]]]

2 个答案:

答案 0 :(得分:3)

此代码按预期工作。当我点击“Click Me!”时,在查看开发者工具(Chrome)中的元素时,我看到该类在“awesomeclass”之间切换并消失:

 (defonce app-state (atom {:some-key true}))

 (defn main []
   (om/root
     (fn [app owner]
       (reify
         om/IRender
         (render [_]
           (html
            [:div {:class (when (:some-key app) "awesomeclass")}
             "Some text!"
             [:a {:on-click #(om/transact! app :some-key not)}
              "Click Me!"]]))))
     app-state
     {:target (. js/document (getElementById "app"))}))  

正如rojoca所指出的,问题可能在于您更新app-state的方式,请考虑使用om/transact!om/update!。如果您遇到问题,请发布更新状态的代码。

注意:我在Chestnut中运行此功能。

答案 1 :(得分:0)

您应该使用关键字:className代替:class