ReactJS - Is there a way to trigger a method by pressing the 'Enter' key inside <input/>?

前端 未结 4 709
长情又很酷
长情又很酷 2020-12-31 07:46

Using only onChange and value and while focused inside a , preferably without jQuery, is there a way to trigger a method by pressing

4条回答
  •  情话喂你
    2020-12-31 08:41

    What you can do is use React's key events like so:

    
    

    Now, to detect enter key, change the enterPressed function to:

    enterPressed(event) {
        var code = event.keyCode || event.which;
        if(code === 13) { //13 is the enter keycode
            //Do stuff in here
        } 
    }
    

    So what this does is add an event listener to the input element. See React's Keyboard Events. The function enterPressed is then triggered on event, and now enterPressed detects the key code, and if it's 13, do some things.

    Here's a fiddle demonstrating the event.


    Note: The onKeyPress and onKeyDown events trigger instantaneously on user press. You can use onKeyUp to combat this.

提交回复
热议问题