请参阅 re-frame todomvc视图命名空间:
该文件包含以下定义
(def todo-edit (with-meta todo-input
{:component-did-mount #(.focus (r/dom-node %))}))
这是从 todo-item 函数调用的。
我知道'component-did-mount'是react.js组件生命周期中的一个阶段,但我不明白这个def的目的和含义。为什么有必要?
请解释。
请参阅 re-frame todomvc视图命名空间:
该文件包含以下定义
(def todo-edit (with-meta todo-input
{:component-did-mount #(.focus (r/dom-node %))}))
这是从 todo-item 函数调用的。
我知道'component-did-mount'是react.js组件生命周期中的一个阶段,但我不明白这个def的目的和含义。为什么有必要?
请解释。
目的完全是提供component-did-mount生命周期功能。
def 正在创建todo-edit,它只是在todo-input挂载 dom 节点时将运行一些代码。请注意,Reagent 组件是在 dom 节点存在之前运行的函数,因此您通常不能执行诸如调用焦点之类的操作。如果它们返回一个函数,则该函数会一直运行渲染,您不想调用焦点,否则表单将无法使用。
Reagent 在作为元数据附加的函数上查找生命周期方法。当这个输入被挂载时,它会在 dom 节点上调用 focus 方法。
设置autofocus属性是一种轻量级的选择。
使用元数据来做到这一点很笨重,应该避免。
Form-3 组件定义如下所示:
(defn my-component
[x y z]
(let [some (local but shared state) ;; <-- closed over by lifecycle fns
can (go here)]
(reagent/create-class ;; <-- expects a map of functions
{:component-did-mount ;; the name of a lifecycle function
#(println "component-did-mount") ;; your implementation
:component-will-mount ;; the name of a lifecycle function
#(println "component-will-mount") ;; your implementation
;; other lifecycle funcs can go in here
:display-name "my-component" ;; for more helpful warnings & errors
:reagent-render ;; Note: is not :render
(fn [x y z] ;; remember to repeat parameters
[:div (str x " " y " " z)])})))
官方的试剂教程并没有展示Form-3组件如何按照上图的方式来做,而是建议大家使用with-meta,比较笨拙劣质。