【问题标题】:Get cursor position, text and key in a React Native TextInput onKeyPress在 React Native TextInput onKeyPress 中获取光标位置、文本和键
【发布时间】:2021-04-14 14:56:47
【问题描述】:

当文本值发生变化时,我需要在onKeyPressonChangeText 中获取TextInput 的当前光标位置、当前文本值和按下的键。

例如,键入“A”应导致以下结果:

  • keyboardKey: 'A'
  • text: 'A'
  • cursorPosition: 1

然后,输入“B”应该会导致:

  • keyboardKey: 'B'
  • text: 'AB'
  • cursorPosition: 2

我试图通过收听onKeyPressonChangeTextonSelectionChange(从startend 获取nativeEvent.selection)来实现这一点,但没有任何成功,因为事件可能异步发生,所以使用@ 987654336@ 或 useRef() 没有帮助获得这三个元素中的任何一个的最新值。

<TextInput
  onChangeText={onChangeText}
  onKeyPress={onKeyPress}
  onSelectionChange={onSelectionChange}
/>

我还尝试从 onKeyPress 中的 TextInput 的引用中获取文本值,但这也不起作用。

最后,尝试将所有三个值设置为状态并在useEffect 中监听它们的变化,但这不起作用,因为如果任何值发生变化,该函数将被执行,我希望每次只调用一次按键。另外,由于某种原因,我没有得到cursorPositiontext 的最新值。

useEffect(() => {
    console.log('useEffect', keyboardKey, cursorPosition, text)
  }, [keyboardKey, cursorPosition, text]);

【问题讨论】:

    标签: react-native react-native-textinput


    【解决方案1】:

    我认为没有办法可以从 TextInput 本身获取光标位置值。你必须自己实现它。您可以使用 onKeyPress 属性来检查按下了什么键并增加一个应该处于如下状态的计数器:

    const [cursorPosition, setCursorPosition] = useState(0);
    const [text, setText] = useState("");
    
    const onKeyPress = ({ nativeEvent: { key: string } }) => {
        // Logic to check what key is pressed if needed
        // Here I put +1 for this simple example, but you can put whatever value you want here
        setCursorPosition(cursorPosition + 1);
    };
    
    const onChangeText = (newText: string) => {
        setText(newText);
    }
    
    <TextInput onKeyPress={onKeyPress} onChangeText={onChangeText} />
    

    然后您可以使用setCursorPosition 函数更新您的光标位置,然后从cursorPosition 读取它。 text 也是如此。

    【讨论】:

      猜你喜欢
      • 2016-02-14
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多