可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
In my React Native app, I am trying to set the cursor position of a TextInput
to a particular position (eg. to the 5th character) but am have trouble doing so as the documentation is lacking a little. I suspect it has something to do with the 'setSelection' property of TextInput
but I cannot seem to find out what to do.
Has anyone successfully done so?
Thanks.
回答1:
As @this.lau_ says there is a controller property called selection
which accepts an object with keys start and end.
Example:
class ControlledSelectionInput extends Component { state = { selection: { start: 0, end: 0 } } // selection is an object: { start:number, end:number } handleSelectionChange = ({ nativeEvent: { selection } }) => this.setState({ selection }) render() { const { selection } = this.state; return <TextInput selection={selection} onSelectionChange={this.handleSelectionChange} /> } }
You can also programmatically set the selection by getting a ref to the component and using setNativeProps
like this:
this.inputRef.setNativeProps({ selection:{ start:1, end:1 } })
Example:
class SetNativePropsSelectionInput extends Component { inputRef = null render() { const { selection } = this.state; return ( <View> <TextInput ref={this.refInput} /> <Button title="Move selection to start" onPress={this.handleMoveSelectionPress} /> </View> } refInput = el => this.inputRef = el handleMoveSelectionPress = () => this.input.setNativeProps({ selection: { start: 0, end: 0 } }) }
回答2:
There is now a selection property on TextInput
which can be used to set the selection or the caret/cursor position.
回答3:
I just know the native way:
public static void adjustCursor(EditText dgInput) { CharSequence text = dgInput.getText(); if (text instanceof Spannable && text.length() > 0) { Spannable spanText = (Spannable) text; Selection.setSelection(spanText, text.length()); } }
Maybe you can find same method in React Native.
回答4:
I don't see any setSelection
property in the documentation https://facebook.github.io/react-native/docs/textinput.html, nor do I believe this is supported in core.
If you're doing this in Android, I suggest you take Tiny's code and build your own native component. https://facebook.github.io/react-native/docs/native-modules-android.html#content
Of course, you could do the same in iOS if you have the skills... https://facebook.github.io/react-native/docs/native-modules-ios.html#content