How to change TextInput cursor position in React Native?

点点圈 提交于 2021-02-11 13:34:28

问题


I am trying to achieve this behaviour in React Native: The user type for example 5 then ".000" will be added automatically to the TextInput , but the user can add an other number for example 7, the final result should look like "57.000".

I tried to find a workaround but calculating the length of value and add chars accordingly but it didn't work as expected.

Then I found the selection props of the TextInput.

Here is my take on this:

I added this to state

selection: {
  start: 0,
  end: 0
}

Here is my TextInput

<TextInput
        onFocus={setSelection}
        selection={selection}
        keyboardType="numeric"
        onChangeText={(text) => onChangeText("val", text)}
        value={val}
        editable={true}
        selectTextOnFocus={false}
 />

Here is onChangeText method

onChangeText = async (key, value) => {
  var numDots = value;
  if (value.indexOf(".000") === -1) {
    numDots = value + ".000"
  }
  this.setState({ [key]: numDots });
};

And here is the setSelection method

setSelection = () => {
   this.setState({ select: { start: 1, end: 1 } });
};

The problem is whenever I type, the cursor is always focusing on index 0, I think setSelection is not being triggered.

Is there something I'm doing wrong?

I hope someone would help me in this. Thanx in advance.


回答1:


I ended up changing the onFocus prop by onSelectionChange and it's working now.




回答2:


You can do the following things to make it work

class YourComponent extends React.Component{
      constructor(props) {
       super(props);
       this.state = {
       text:'Hello World',
       selection: {
        start: 0,
        end: 0
       }
  };

this.inputRefs = {};
}

   setSelection = () => {
      this.setState({ select: { start: 1, end: 1 } });
      };

    changeText = (val) => {
     this.inputRefs.input.focus();
    }

    render(){
       return(
          <TextInput 
            onFocus={this.setSelection}
            selection={this.state.setSelection} 
            onChangeText={val => {this.changeText(val)}} 
            value={this.state.text}
             refName={ref => {
             this.inputRefs.input = ref;
             }}
            />
       )
    }
} 
The idea is whenever your TextInput calls the onChangeText call-back put the focus on your TextInput through refs, as your component is responding to onFocus call back we will set the selection on that call back


来源:https://stackoverflow.com/questions/62152735/how-to-change-textinput-cursor-position-in-react-native

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