How To Detect "Enter" Keypress in Reagent?

时间:2015-10-06 08:24:51

标签: clojurescript reagent

Given the following code:

  [:input {:type "text"
           :value (:text @app-state)
           :on-change (fn [e]
                        (if (= 31 (.-keyCode e))
                          (println "ENTER")
                          (println "NOT ENTER")))}]

How to change the if condition so that enter keypresses can be distinguished from normal keys? All properties in e except target seem to be null.

2 个答案:

答案 0 :(得分:19)

这是如何解决它:

  1. 你应该听:on-key-press(而不是:on-change), 因为“输入”不会触发:on-change事件(显然不会改变文本)
  2. “enter”的关键代码是 13 ,而不是 31
  3. 使用charCode代替keyCode(不是js中的专家,但keyCode在Firefox中对我不起作用)

    [:input {:type "text"
             :value (:text @app-state)
             :on-key-press (fn [e]
                             (println "key press" (.-charCode e))
                             (if (= 13 (.-charCode e))
                               (println "ENTER")
                               (println "NOT ENTER")))}]
    

答案 1 :(得分:5)

key

[:input
 {:on-key-press
  (fn [e]
    (if (= (.-key e) "Enter")
      (.log js/console "Enter")
      (.log js/console "Not Enter")))}]

同样感兴趣的是:on-key-up:on-key-down