Last active
May 10, 2017 14:15
-
-
Save savelichalex/0cdd767e3adb3bbbab80671a26af61d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component } from 'react'; | |
| class Input extends Component { | |
| static state = { | |
| curPos: null, | |
| } | |
| componentDidUpdate() { | |
| const { | |
| curPos, | |
| } = this.state; | |
| if (curPos) { | |
| this.setCarretPosition(curPos); | |
| } | |
| } | |
| setCarretPosition(position) { | |
| const field = this.inputComp; | |
| if (field == null || position == null) { | |
| return; | |
| } | |
| if ('selectionStart' in field && 'selectionEnd' in field) { | |
| field.selectionStart = position; | |
| field.selectionEnd = position; | |
| } else { // IE | |
| if (field.createTextRange == null) { | |
| return; | |
| } | |
| const range = field.createTextRange(); | |
| range.collapse(true); | |
| range.moveStart('character', position); | |
| range.moveEnd('character', position); | |
| range.select(); | |
| } | |
| } | |
| onChange = (event) => { | |
| if (this.inputComp != null) { | |
| this.setState({ | |
| curPos: Input.getSelectionEnd(event, this.inputComp), | |
| }); | |
| } | |
| this.props.onChange(event); | |
| } | |
| render() { | |
| return <input value={this.props.value} onChange={this.onChange} /> | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment