React Native - Setting TextInput cursor position

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!