这是我的 Clojurescript 代码:
(def focus-wrapper
(with-meta identity
{:component-did-update #(.focus (dom-node %))}))
(defn solution-input []
(let [current-char (subscribe [:current-char])
input (subscribe [:input])]
[focus-wrapper
(fn []
[:input {:type "text"
:auto-focus true
:value (:value @input)
:disabled (:disabled @input)
:on-change #(dispatch [:input-value-updated (.-target.value %)])
:on-key-press #(when (= 13 (.-which %))
(if (= (.-target.value %) (:solution @current-char))
(dispatch [:right-option-picked])
(dispatch [:wrong-option-picked])))}])]))
(defn quiz [props childrn this]
(let [current-char (subscribe [:current-char])
counter (subscribe [:counter])
feedback (subscribe [:feedback])]
(fn []
[:div.panel-container
[:h2 "Quiz"]
[:div.counter (str (:correct-guesses @counter) "/" (:total-guesses @counter))]
[:div.char (:hint @current-char)]
[solution-input]
[:div.feedback (when (not= @feedback "off") @feedback)]
[:button {:type "button"
:on-click #(dispatch [:next-char])}
"Skip"]
[:button {:type "button"
:on-click #(dispatch [:panel-changed "result"])}
"Finish"]])))
请注意,我也在使用重新框架。我在我的 app-db 中保留输入状态(其值和禁用状态)并在我的组件中订阅它们。因此,一旦这些道具中的任何一个发生变化(这就是我的焦点包装器的用途),就很容易强制将焦点放在组件上。
尽管如此,一旦单击跳过按钮,我正在努力寻找一种方法来强制关注输入。据我所知,这是 React 中一个典型的合理用例ref
,它在 Reagent 中的工作方式似乎有所不同。
有人可以推荐一种方法来解决 Reagent/re-frame 中这个特定的焦点管理问题吗?