【问题标题】:Getting props in reagent's :reagent-render function在试剂的 :reagent-render 函数中获取道具
【发布时间】:2018-02-16 02:00:28
【问题描述】:

我可以使用 Javascript 的 react 版本

  this.props

但是我可以用什么来给道具

  :reagent-render

回调?

I am trying to do as done here 在 Chart.js 第 14 行。

【问题讨论】:

    标签: clojurescript reagent


    【解决方案1】:

    要回答您的问题,您可以通过执行以下操作访问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 component 以更新自身。

    Reagent 的功能之一是提供检测更改和更新组件的功能,通常使用atom。请参阅Managing State in Reagent 了解更多信息。

    您要做的正是Re-frame Framework 正在帮助管理的事情。您设置了一个数据存储,当存储发生变化时,它会向订阅者(React 元素)发出信号以进行相应的更新,而您不必自己处理信号变化。

    在某些极端情况下,需要利用生命周期事件,尤其是图表和其他绘图库,但如果您发现试剂 atoms 和/或 re-frame library 不足以满足您的需求,我可能会建议您重新访问.希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      据我所知,您接受来自用户的一些 Hiccup 数据作为字符串,对吗?然后尝试将其评估为user 命名空间,其中仅加载了reagent 库?

      首先,您构建的代码越多以进行评估,就越难理解。你可以使用这样的东西:

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

      另外,为了防止输入错误,最好使用 Schema 或 clojure.spac 库来验证用户的输入。由于 read-string 返回一个数据结构,因此也可以使用这两个进行检查。所以在开始评估之前你会看到一个错误。

      【讨论】:

        猜你喜欢
        • 2020-12-24
        • 1970-01-01
        • 1970-01-01
        • 2018-10-28
        • 2018-09-19
        • 1970-01-01
        • 1970-01-01
        • 2017-05-13
        • 1970-01-01
        相关资源
        最近更新 更多