当文本值在onKeyPress
或onChangeText
中发生变化时,我需要获得TextInput
的当前光标位置、当前文本值和按下的键。
例如,键入";A";应产生以下结果:
keyboardKey: 'A'
text: 'A'
cursorPosition: 1
然后,键入"B";应导致:
keyboardKey: 'B'
text: 'AB'
cursorPosition: 2
我试图通过监听onKeyPress
、onChangeText
和onSelectionChange
(从nativeEvent.selection
获取start
和end
(来实现这一点,但没有成功,因为这些事件可能是异步发生的,所以使用useState()
或useRef()
在任何事件中获取这三个值的最新值都没有帮助。
<TextInput
onChangeText={onChangeText}
onKeyPress={onKeyPress}
onSelectionChange={onSelectionChange}
/>
我还尝试从onKeyPress
中TextInput
的引用中获取文本值,但这也不起作用。
最后,尝试将这三个值都设置为状态,并在useEffect
中监听它们的变化,但这不起作用,因为如果任何值发生变化,函数都会被执行,我希望每次按键只调用一次。此外,由于某种原因,我没有得到cursorPosition
和text
的最新值。
useEffect(() => {
console.log('useEffect', keyboardKey, cursorPosition, text)
}, [keyboardKey, cursorPosition, text]);
我认为没有办法从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
也是如此。