问题描述
在React Native TextInput中,如何知道用户键入的字符的索引?
示例:这是乔
如果用户将光标移动到“ is”一词之后并键入“ This not joe”。
我想知道用户键入的字符的索引“”,然后是“ n”,然后是“ o”,然后是“ t”。
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}
/>