在TextInput中获取准确的当前光标位置

时间:2019-06-10 03:37:18

标签: javascript ios react-native

我正在尝试获取TextInput字段中的当前光标位置,但根据将文本输入到字段中所用的内容,我没有获得准确的位置。 onSelectionChange似乎不是我要解决的问题的解决方案。

如果我在模拟器上使用键盘,则它可以准确地更新selectChange,但是如果我在不更改文本的情况下移动光标,则它不能给我准确的光标位置。

为了证明这一点,我提供了以下代码。要运行它,您必须具有React Debugger或某种方式来查看console.log的输出,并且可能需要为其设置一个新项目。

要设置一个新项目: react-native init TestTextInput --template typescript

export default class App extends Component<Props> { ... }中的App.tsx替换为:

export default class App extends Component<Props, {[key: string]: string}> {
  constructor(props: any) {
    super(props);
    this.state = {
      input: '',
    };
    this.addChar = this.addChar.bind(this);
    this.reset = this.reset.bind(this);
  }

  public textInput: TextInput|null = null;
  public currentSelection: { end: number, start: number } = { end: 0, start: 0};

  addChar(input: string) 
  {
    console.log('==== button pushed ====');
    console.log(this.currentSelection);
    var state: any = Object.assign({}, this.state);
    state.input += input;
    this.setState(state);
  }

  reset(input: string) 
  {
    console.log('==== keyboard pressed ====');
    console.log(this.currentSelection);
    var state: any = Object.assign({}, this.state);
    state.input = input;
    this.setState(state);
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={[{borderWidth: 1, borderColor: 'black', fontSize: 25}]}
          value={this.state.input}
          ref={(input) => this.textInput = input}
          onChangeText={(e) => this.reset(e)}
          onSelectionChange={(e) => this.currentSelection = e.nativeEvent.selection }
        ></TextInput>
        <Button title="Input A" onPress={() => this.addChar('a')} />
        <Button title="Input B" onPress={() => this.addChar('b')} />
      </View>
    );
  }
}

一旦您将其与调试器同步,并使其在模拟器中运行,您会注意到,如果我使用键盘上的左右键,它不能准确地给我光标位置。如果像使用手指一样在电话(带放大镜)上使用鼠标来更改光标位置,它也无法提供准确的光标位置。

是否有一种方法可以获取当前光标位置,而与onChangeText或onSelectionChange无关,而无需迅速编写内容?

TextInput类上,有一个setNativeProperties方法可以设置selection,我想知道是否有能力获得这些属性,而不仅仅是设置它们。

0 个答案:

没有答案