试剂:component-did-mount

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

尽管如此,这对我并没有起作用。我做错了什么?


1
不是直接的答案,但如果您将autoFocus属性设置为true,那应该可以工作。 - Brigand
3个回答

14

正如sbensu所说,with-meta似乎只能在reagent函数中使用。这意味着它可以与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"}]]))

对于那些遇到困难的人,您需要使用(reagent/as-element [chat-input])来正确渲染它。 - Vans S

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

你是对的。Reagent似乎只在应用到一个带有元数据的函数时才起作用。不幸的是,它似乎也不能与匿名函数一起使用。 - Brendanator

1

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接