要更改React Native中TextInput的光标位置,可以使用setSelectionRange
方法
import React, { useRef } from 'react';
import { TextInput } from 'react-native';
const App = () => {
const inputRef = useRef(null);
const changeCursorPosition = (position) => {
inputRef.current.setSelectionRange(position, position);
};
return (
<>
<TextInput
ref={inputRef}
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={(text) => console.log(text)}
/>
<button onClick={() => changeCursorPosition(2)}>设置光标位置为2</button>
</>
);
};
export default App;
在这个例子中,光标位置设置为2。你可以根据需要更改changeCursorPosition
函数中的参数来更改光标位置。
领取专属 10元无门槛券
手把手带您无忧上云