如何在React Native中更改TextInput光标位置?

时间:2020-06-02 13:07:29

标签: react-native react-native-android react-native-ios

我正在尝试在React Native中实现此行为:例如5的用户类型,然后将“ .000”自动添加到TextInput,但是用户可以添加其他数字,例如7,最终结果应为“ 57.000”。

我试图找到一种解决方法,但计算出值的长度并相应地添加字符,但未按预期工作。

然后我发现了selection的{​​{1}}道具。

这是我的看法:

我将此添加到状态

TextInput

这是我的selection: { start: 0, end: 0 }

TextInput

这是onChangeText方法

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

这是setSelection方法

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

问题是,每当我键入时,光标始终将焦点放在索引setSelection = () => { this.setState({ select: { start: 1, end: 1 } }); }; 上,我认为0没有被触发。

我在做错什么吗?

我希望有人可以帮助我。谢谢。

2 个答案:

答案 0 :(得分:1)

我最终用onFocus更改了onSelectionChange道具,并且现在可以使用了。

答案 1 :(得分:0)

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
相关问题