How to handle the `onKeyPress` event in ReactJS?
I am working with React 0.14.7, use onKeyPress
and event.key
works well.
handleKeyPress = (event) => { if(event.key === 'Enter'){ console.log('enter press here! ') }}render: function(){ return( <div> <input type="text" id="one" onKeyPress={this.handleKeyPress} /> </div> );}
For me onKeyPress
the e.keyCode
is always 0
, but e.charCode
has correct value. If used onKeyDown
the correct code in e.charCode
.
var Title = React.createClass({ handleTest: function(e) { if (e.charCode == 13) { alert('Enter... (KeyPress, use charCode)'); } if (e.keyCode == 13) { alert('Enter... (KeyDown, use keyCode)'); } }, render: function() { return( <div> <textarea onKeyPress={this.handleTest} /> </div> ); } });
render: function(){ return( <div> <input type="text" id="one" onKeyDown={this.add} /> </div> );}
onKeyDown
detects keyCode
events.