React.js controlled text cursor focus issue

杀马特。学长 韩版系。学妹 提交于 2019-12-05 02:23:52

This is how React updates an input field's value:

node.setAttribute(attributeName, '' + value);

When you set value attribute using that method, the caret goes to the beginning of the field, regardless of using React. You can see what I am saying in this fiddle - https://jsfiddle.net/5v896g3q/ (Just try and position the cursor in the field, between changes).

According to MDN, setAttribute is unstable when dealing with value. The recommended way of changing value is by accessing the value property of the element, like element.value = newValue. If you use that approach, all seems to go as expected.

This is all I can tell for sure. Now let's speculate a little. When you type anything in that field, you are:

  1. updating the value of the input
  2. reading that value, and sending to React as state
  3. React updates the value of the input, with the new state

When you are typing on the field, step 3 is likely to have no impact, because when the value comes back, the input already got it right. Except on the case with the float number. When your field reads 1., the actual value React updates the field with is 1. And React uses the evil method (setAttribute).

So, a workaround I found was setting the value of the field, using the proper method, before React touches it, on componentWillUpdate:

componentWillUpdate(nProps, nState){
  this.refs.input.value = '0' + nState.value
}

The problem there, is that it is "numerizing" the value on every change, meaning I won't be able to have a point (1.). For that reason, I will only edit the input in case new value is 2 characters shorter than the old one (point + digit after point):

componentWillUpdate(nProps, nState){
  if(this.state.value.length - nState.value.length === 2){
    this.refs.input.value = '0' + nState.value
  }
}

Working example - https://jsfiddle.net/bsoku268/3/

note: the fiddle is for demonstration purposes, and not supposed to be a bulletproof solution, as there are many ways of interacting with an input field, such as copy & paste, drag & drop, autofill, etc

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