javascript - key binding in react.js -
was trying implement key binding in react.js. did research, still wondering what's cleanest way it. example,
if (event.keycode == 13 /*enter*/) { function() } if (event.keycode == 27 /*esc*/) { anotherfunction() }
i ended binding keydown event when component mounted , unmounted:
...
componentdidmount: function() { $(document.body).on('keydown', this.handlekeydown); }, componentwillunmount: function() { $(document.body).off('keydown', this.handlekeydown); }, handlekeydown: function(event) { if (event.keycode == 13 /*enter*/) { this.okaction(); } if (event.keycode == 27 /*esc*/) { this.cancelaction(); } }, render: function() { return this.state.showdialog ? ( <div classname="dialog" onkeydown={this.handlekeydown}>
...
there's better way this. function used part of dialog component: https://github.com/changey/react-dialog