在 reagent 的 :reagent-render 函数中获取 props

4
2个回答

5
为了回答你的问题,你可以像这样在reagent-render中访问componentprops
(ns chartly.core
  (:require
    [reagent.ratom :as ra]
    [reagent.core :as r]))

(defn data-fn [implicit-this]
  ;; use implicit-this as needed, which is equivalent to "this"
  ;; From create-class docs -
  ;;    :component-did-mount (fn [this])
 )

(defn chart-render []
  (let [comp     (r/current-component)     ;; Reagent method
        r-props  (r/props comp)            ;; Reagent method
        js-props (.-props (clj->js comp))]
      (js/console.log "PROPS" r-props)     ;;--  etc...
    [:div {:style {:width 100}}]))

(def data (ra/atom {})) ;;--> see more info on reagent-atom

(defn chart-component []
  (r/create-class
   {:component-did-mount data-fn
    :display-name "chart-component"
    :reagent-render chart-render}))

    To use - 
    [chart-component]

然而,这是一种反模式,并且很难管理,因为您正在尝试使用component-did-mount在内部更新数据属性,完成后需要手动通知React组件进行更新。
Reagent的一个特点是它提供了检测更改并更新组件的功能,通常使用atom实现。有关更多信息,请参见在Reagent中管理状态
您要做的正是Re-frame框架所帮助管理的内容。您设置一个数据存储库,当存储库更改时,它会向订阅者(React元素)发出信号以相应地进行更新,而您不必自己处理信号变化。
在某些边缘情况下,连接到生命周期事件是必要的,特别是对于图表和其他绘图库,但如果发现reagent的atoms和/或re-frame库无法满足您的需求,建议重新审视。希望能帮到您。

1

据我所见,您接受用户提供的一些Hiccup数据作为字符串,对其进行评估,并加载reagent库,将其放入user命名空间中,是这样吗?

首先,您构建用于评估的代码越多,理解起来就越困难。您可以使用类似以下内容的东西:

(binding [*ns* user-ns] (eval (read-string user-data)))

此外,为了避免错误的输入,最好使用Schema或clojure.spac库验证用户的输入。由于read-string返回一个数据结构,也可以使用这两个库进行检查。这样,在开始评估任何内容之前,您就会看到错误。

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