reactjs - Keybindings in react -
i've been trying figure out keybindings in react , i'm bit stuck.
i placed onkeypress , tried onkeydown on input. allowed me handle letters , enter key.
however haven't been able find way handle arrow keys , esc key without creating document.addeventlistener('keydown'', this.onkeypress)
anyone have better solution?
you can use focus
, blur
events control lifecycle of event handler.
render() { return ( <input ref={inputloaded} type="text" /> ); }, inputloaded(input) { input.addeventlistener('focus', this.addeventlisteners); input.addeventlistener('blur', this.removeeventlisteners); this.input = input; }, componentwillunmount() { this.input.removeeventlistener('focus', this.addeventlisteners); this.input.removeeventlistener('blur', this.removeeventlisteners); window.removeeventlistener('keydown', this.handlekey); }, addeventlisteners() { window.addeventlistener('keydown', this.handlekey); }, removeeventlisteners() { window.removeeventlisteners('keydown', this.handlekey); }, handlekey(event) { // gets called if input focused. // key }
alternatively, use focus
, blur
events control state
variable, check whether input has focus inside handlekey
method, before doing work.
Comments
Post a Comment