How To Detect “Enter” Keypress in Reagent?

五迷三道 提交于 2019-12-12 08:24:51

问题


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.


回答1:


that's how to fix it:

  1. you should listen to :on-key-press (rather than :on-change), because "enter" doesn't trigger :on-change event (it obviously doesn't change the text)
  2. key code for "enter" is 13, not 31
  3. use charCode instead of keyCode (not an expert in js, but keyCode doesn't work for me in 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")))}]
    



回答2:


With key.

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

Also of interest is :on-key-up and :on-key-down.



来源:https://stackoverflow.com/questions/32965086/how-to-detect-enter-keypress-in-reagent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!