javascript - Focus on next field when pressing enter React.js -
i find way focus on next field when click enter in input using react.js
@autobind handlekeypress(event){ if(event.key === 'enter'){ this.refs.email.focus(); } } @autobind handlekeypressemail(event){ if(event.key === 'enter'){ this.refs.zip_code.focus(); } } <input onkeypress={this.handlekeypress} ref = 'name' /> <input onkeypress={this.handlekeypressemail} ref = 'email' /> <input ref = 'zip_code' />
this best way have found far, don't want repeat myself creating function everytime want happen. there better , cleaner way implement this?
you can use componentdidmount , auto bind refs through for-in loop.
http://codepen.io/jzmmm/pen/pzzgrx?editors=0010
constructor() { super(); this._handlekeypress = this._handlekeypress.bind(this); } // loop through ref's object, , bind each of them onkeypress componentdidmount() { (let x in this.refs) { this.refs[x].onkeypress = (e) => this._handlekeypress(e, this.refs[x]); } } // checks enter key (13), checks if next node input // focuses next input box _handlekeypress(e, field) { if (e.keycode === 13) { e.preventdefault(); // prevent form submission if button present let next = this.refs[field.name].nextsibling; if (next && next.tagname === "input") { this.refs[field.name].nextsibling.focus(); } } } render() { return ( <form> <input type="text" name="name" ref='name' /> <input type="text" name="email" ref='email' /> <input type="text" name="zip_code" ref='zip_code' /> </form> ); }
Comments
Post a Comment