@H_301_1@在我的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 <TextInput selection={selection} onSelectionChange={this.handleSelectionChange} /> } }
您还可以通过获取组件的引用并使用如下setNativeProps以编程方式设置选择:
this.inputRef.setNativeProps({ selection:{ start:1,end:1 } })
例:
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 } }) }