嵌套从函数返回的 reagent hiccup 元素的首选语法是什么?

What is the preferred syntax for nesting a reagent hiccup element that is returned from a function?

给定一个 return 元素的函数:

(defn title []
  [:h1 "Hello World"])

将其嵌套在另一个组件中的首选方式是什么?

我在教程中看到它是通过将函数调用包装在向量中完成的:

[:div {:class "app"}
  [title]]

但这对我来说有点奇怪,因为 title 的 return 值本身就是一个向量,因此会扩展为 [[:h1 "Hello World"]]。外向量会怎样?

它也可以只计算内联函数:

[:div {:class "app"}
  (title)]

但我不确定这是否是个好主意,因为混合使用括号和方括号可能难以阅读。

有什么意见吗?

这对试剂比对打嗝更具体(ish html-生成器)-- 它可能适用于也可能不适用于不同的框架或在 服务器端。

试剂用函数代替“标签”并将其视为反应 零件。请注意 [title] 不是 调用 函数。它是 向量,包含对函数的引用。

所以这里的区别在于,你是否希望 title 被当作 一个组件(及其附带的所有组件(使用 [title] 时))或者如果 您只需在那里调用 (title),它会将结果放在向量中。

有一整个 tutorial page 致力于此:

So, which variation of greet-family (square vs round) should I choose, and why?

The answer to "which?" is easy: you almost certainly want the square version. "why?" takes more explanation ...

First off, let's acknowledge that both variations will ultimately produce the same DOM, so in that respect they are the same.

Despite this identical outcome, they differ in one significant way:

  1. the square version will create each greet child as a distinct React component, each with its own React lifecycle, allowing them to re-render independently of siblings.
  2. The round version causes the greet hiccup for all children to be incorporated into the hiccup returned by the parent, forming one large data structure, parent and children all in together. So, each time the parent re-renders, all the greet children are effectively re-rendered too. React must then work out what, in this tree, has changed.

As a result, the square version will be more efficient at "re-render time". Only the DOM which needs to be re-rendered will be done. At our toy scale in this tutorial it hardly matters but, if greet was a more substantial child component, this gain in efficiency could be significant.