强制试剂组件在窗口调整大小时更新

时间:2016-10-03 12:03:17

标签: clojurescript reagent

我正在尝试实现一个试剂组件,它可以跟踪它的外部html元素的实际计算大小。以下作品:

(defn i-show-my-size []
  (let [size (r/atom nil)]
    (r/create-class {:component-will-mount
                     (fn [this]
                       (set! (.-onresize js/window)
                             (r/force-update this)))
                     :reagent-render
                     (fn []
                       [:div {:ref #(when % (reset! size (let [bb (.getBoundingClientRect %)]
                                                           [(.-width bb) (.-height bb)])))}
                        (prn-str @size)])})))

有没有更好的方法呢?例如。我是否需要创建类符号或者可能没有?

2 个答案:

答案 0 :(得分:2)

实际上,您可以同时使用r / with-let和r / current-component来使其不使用form-3组件:

(defn get-client-rect [node]
  (let [r (.getBoundingClientRect node)]
    {:left (.-left r), :top (.-top r) :right (.-right r) :bottom (.-bottom r) :width (.-width r) :height (.-height r)}))

(defn size-comp []
  (r/with-let [size (r/atom nil)
               this (r/current-component)
               handler #(reset! size (get-client-rect (r/dom-node this)))
               _ (.addEventListener js/window "resize" handler)]
    [:div "new size " @size]
    (finally (.removeEventListener js/window "resize" handler))))

答案 1 :(得分:0)

0.6.0引入with-lethttp://reagent-project.github.io/news/news060-alpha.html)他们的示例(如下)与您的用例非常相似:

(defn mouse-pos-comp []
  (r/with-let [pointer (r/atom nil)
               handler #(swap! pointer assoc
                               :x (.-pageX %)
                               :y (.-pageY %))
               _ (.addEventListener js/document "mousemove" handler)]
    [:div
     "Pointer moved to: "
     (str @pointer)]
    (finally
      (.removeEventListener js/document "mousemove" handler))))