在试剂/重构中渲染两个组件

Render two components in reagent / reframe

我有一些代码:

(defn second-panel []
    [:div
     [:h1 "Hello "]
     ])

(defn root-container []
  (second-panel)
  (let [name (re-frame/subscribe [::subs/name])]
    [:div
     [:h1 "Hello from " @name]
     ]))

但只有 root-container 组件呈现。为什么我的 second-panel 函数没有渲染?非常感谢。

您必须将 (second-panel) 添加到您的 div。当前忽略 (second-panel) 的 return 值。

(defn root-container []
  (let [name (re-frame/subscribe [::subs/name])]
    [:div
     (second-panel)
     [:h1 "Hello from " @name]
     ]))

从函数返回多个虚拟 DOM 元素而不将它们包装在容器元素中的正确解决方案是使用 Fragment。在 reagent 中,这是由 :<> 特殊关键字处理的。

(defn second-panel []
  [:div
   [:h1 "Hello "]])

(defn root-container []
  (let [name (re-frame/subscribe [::subs/name])]
    [:<>
     [second-panel]
     [:div
      [:h1 "Hello from " @name]
      ]]))

;; or, with the nested let. both variants are fine.

(defn root-container []
  [:<>
   [second-panel]
   (let [name (re-frame/subscribe [::subs/name])]
     [:div
      [:h1 "Hello from " @name]
      ])])

(second-panel)[second-panel] 也有不同,因为 (second-panel) 实际上会直接调用该函数,这意味着它不会像常规试剂函数那样运行,而是成为呼叫者,召集者。对于所有 "component" 类型的函数,您应该更喜欢 [second-panel] 表示法。