18

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

(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"}]]))

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

4

3 回答 3

14

正如 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"}]]))
于 2014-12-24T12:21:32.417 回答
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"}]]))
于 2014-12-23T18:35:26.600 回答
1

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

(defn chat-input []
  [:input {:type "text" :auto-focus true}]])
于 2019-11-29T00:38:10.623 回答