React Native – 设置TextInput游标位置

在我的React Native应用程序中,我正在尝试将TextInput的光标位置设置为特定位置(例如,到第5个字符)但由于文档缺少一点,我很难这样做。 我怀疑它与TextInput的’setSelection’属性有关,但我似乎无法找到该做什么。

有没有人成功这样做过?

谢谢。

正如@ this.lau_所说,有一个名为selection的控制器属性,它接受一个带有键start和end的对象。

例:

 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  } } 

您还可以通过获取组件的引用并使用setNativeProps以编程方式设置选择:

 this.inputRef.setNativeProps({ selection:{ start:1, end:1 } }) 

例:

 class SetNativePropsSelectionInput extends Component { inputRef = null render() { const { selection } = this.state; return (     } refInput = el => this.inputRef = el handleMoveSelectionPress = () => this.input.setNativeProps({ selection: { start: 0, end: 0 } }) } 

现在TextInput上有一个选择属性,可用于设置选择或插入符/光标位置。

我只知道原生的方式:

 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()); } } 

也许你可以在React Native中找到相同的方法。

我在文档https://facebook.github.io/react-native/docs/textinput.html中没有看到任何setSelection属性,我也不相信它在核心中受支持。

如果您在Android中执行此操作,我建议您使用Tiny的代码并构建自己的本机组件。 https://facebook.github.io/react-native/docs/native-modules-android.html#content

当然,如果你有技能,你可以在iOS中做同样的事情… https://facebook.github.io/react-native/docs/native-modules-ios.html#content