How can I set the cursor position in a TextInput field with a button and still be able to change the position normally by pressing on a certain point on the text?
You have to keep track of your selection manually (done through selection
and onSelectionChange
properties):
export default function App() {
const [text, setText] = React.useState("test")
const [selection, setSelection] = React.useState({start:0, end: 0})
return (
<View style={{flex: 1, justifyContent: 'center'}}>
<TextInput
style={{borderWidth: 1}}
value={text}
onChangeText={newText => setText(newText)}
selection={selection}
onSelectionChange={({ nativeEvent: { selection, text } }) => setSelection(selection)}
/>
<Button
title="Press me"
onPress={() => {
setSelection({start: 2, end: 2})
}}
/>
</View>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.