React Native TextInput:如何知道用户键入的字符的索引

问题描述

在React Native TextInput中,如何知道用户键入的字符的索引?

示例:这是乔

如果用户将光标移动到“ is”一词之后并键入“ This not joe”。

我想知道用户键入的字符的索引“”,然后是“ n”,然后是“ o”,然后是“ t”。

我确实得到了用户在onKeyPress中输入的内容

const keyPressHandler = (e) => {
    console.log(e.nativeEvent.key + "pressed");
    console.log(e.nativeEvent);
    setKeypressed(e.nativeEvent.key);
  }

This is my TextInput field
<TextInput 
    {...props}
    style = {styles.textField}
    multiline = {true}
    textAlignVertical = 'top'
    placeholder = 'Enter your text'
    onChangeText={onChangeTextHandler}
    onChange = {onChangeHandler}
    onBlur={lostFocusHandler}
    onKeyPress = {keyPressHandler}
    value = {postText}
     />

我正在编写一个组件,其中当用户键入“ @”时,我在其中显示要在帖子中提及他们的用户列表,因此我需要知道键入字符的索引,然后需要知道键入之前是否有空格字符,然后仅显示用户列表。

解决方法

每次使用@符号更改值时,我都会使用一种状态来保存文本输入,然后使用“效果”来检查字符串。

类似的东西:

import {useEffect,useState} from 'react-native';

const MyTextInput = () => {
     const [value,setValue] = useState(null);

     useEffect(() => {
         if(value.indexOf('@') !== -1){
            const index = value.indexOf('@');
            ** Do Something **
         }
     },[value]);

return (
     <TextInput 
          {...props}
          style = {styles.textField}
          multiline = {true}
          textAlignVertical = 'top'
          placeholder = 'Enter your text'
          onChangeText={setValue}
          onChange = {onChangeHandler}
          onBlur={lostFocusHandler}
          value={value}
          />
)
}

我建议使用上述方法的原因是onKeyPress函数不适用于android硬件键盘,而上述方法适用于所有情况。

上面的方法还将为您提供@的索引,以便您可以在其后得到子字符串。

注意:indexOf方法将仅查找字符串中的第一个@。对于用户可以输入多个@的方案,正则表达式可能会有所帮助。

,

onSelectionChange给出光标位置。起点和终点位置与移动光标相同。如果选择某项,则将有所不同/

 const selectionChangeHandler = (e) => {
    console.log("Selection change handler Start = " + e.nativeEvent.selection.start + "End =" + e.nativeEvent.selection.end);
    setCursorPosition(e.nativeEvent.selection);
  };

<TextInput 
    {...props}
    style = {styles.textField}
    multiline = {true}
    textAlignVertical = 'top'
    placeholder = 'Enter your text'
    onChangeText={onChangeTextHandler}
    onChange = {onChangeHandler}
    onBlur={lostFocusHandler}
    onKeyPress = {keyPressHandler}
    onSelectionChange = {selectionChangeHandler}
    selectTextOnFocus = {false}
    value = {postText}
    ref={postTextInputField}

     />

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...