Stop cursor jumping when formatting number in React

冷暖自知 提交于 2019-12-05 00:48:32

Hi there has been a discussion about this on the issues in github.com https://github.com/facebook/react/issues/955 see the comment on Nov 30th

You probably want to be using setstate on input components aswell.

An easy solution for loosing cursor/caret position in the React's <input /> field that's being formatted is to manage the position yourself:

onChange(event) {

  const caret = event.target.selectionStart
  const element = event.target
  window.requestAnimationFrame(() => {
    element.selectionStart = caret
    element.selectionEnd = caret
  })

  // your code
}

The reason your cursor position resets is because React does not know what kinds of changes you are performing (what if you are changing the text completely to something shorter or longer?) and you are now responsible for controlling the caret position.

Example: On one of my input textfields I auto-replace the three dots (...) with an ellipsis. The former is three-characters-long string, while the latter is just one. Although React would know what the end result would look like, it would not know where to put the cursor anymore as there no one definite logical answer.

Khyati
onKeyUp(ev) {
  const cardNumber = "8318 3712 31"
  const selectionStart = ev.target.selectionStart; // save the cursor position before cursor jump
  this.setState({ cardNumber, }, () => {
    ev.target.setSelectionRange(selectionStart, selectionStart); // set the cursor position on setState callback handler
  });
}
set value(val) { // Set by external method
    if(val != this.state.value) {
        this.setState({value: val, randKey: this.getKey()});
    }
}

getKey() {
    return 'input-key' + parseInt(Math.random() * 100000);
}

onBlur(e) {
    this.state.value = e.target.value; // Set by user
    if(this.props.blur) this.props.blur(e);
}

render() {
    return(
<input className="te-input" type="text" defaultValue={this.state.value} onBlur={this.onBlur} key={this.state.randKey} />
    )
}

If you need an Input that's both editable without cursor move and may be set from outside as well you should use default value and render the input with different key when the value is changed externally.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!