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

问题描述 投票:0回答:1

我试图在React Native中实现这种行为。比如用户输入5,那么".000 "就会被自动添加到... TextInput 但用户可以添加其他数字,例如7,最终结果应该是 "57.000"。

我试图找到一个变通的方法,但计算值的长度,并相应地添加字符,但它没有像预期的那样工作。

然后我找到了 selection 阁下 TextInput.

这是我的看法。

我把这个加上去

selection: {
  start: 0,
  end: 0
}

这是我的 TextInput

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

下面是onChangeText方法

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

下面是setSelection方法

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

问题是每当我打字时,光标总是集中在索引上。0我想 setSelection 没有被触发。

是不是我做错了什么?

希望有人能帮我解决这个问题。先谢谢了。

react-native react-native-android react-native-ios
1个回答
0
投票

我最终改变了 onFocusonSelectionChange 而现在它的工作。


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
© www.soinside.com 2019 - 2024. All rights reserved.