试剂:组件安装

时间:2014-12-22 12:18:14

标签: reactjs clojurescript reagent

我正在尝试将初始焦点设置在输入元素

(defn initial-focus-wrapper [element]
  (with-meta element
    {:component-did-mount #(.focus (reagent/dom-node %))}))

(defn chat-input []
  (fn []
    [initial-focus-wrapper
      [:input {:type "text"}]]))

但这对我不起作用。我做错了什么?

3 个答案:

答案 0 :(得分:13)

正如sbensu所说with-meta似乎只在函数中使用试剂。这意味着它可以与identity一起使用来生成希望的可重用包装

(def initial-focus-wrapper 
  (with-meta identity
    {:component-did-mount #(.focus (reagent/dom-node %))}))

(defn chat-input []
  (fn []
    [initial-focus-wrapper
      [:input {:type "text"}]]))

答案 1 :(得分:5)

我认为with-meta应该将函数作为参数。来自文档:

(def my-html (atom ""))

(defn plain-component []
  [:p "My html is " @my-html])

(def component-with-callback
  (with-meta plain-component
    {:component-did-mount
     (fn [this]
       (reset! my-html (.-innerHTML (reagent/dom-node this))))}))

所以你的代码应该是:

(defn initial-focus-wrapper [element]
  (with-meta element
    {:component-did-mount #(.focus (reagent/dom-node %))}))

(defn chat-input []
  [initial-focus-wrapper
    (fn []
      [:input {:type "text"}]]))

答案 2 :(得分:0)

设置焦点在给定组件上的另一种方法是使用“:auto-focus true”属性:

(defn chat-input []
  [:input {:type "text" :auto-focus true}]])