android – React Native – 设置TextInput游标位置

前端之家收集整理的这篇文章主要介绍了android – 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 <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
        }
    })
}
原文链接:https://www.f2er.com/android/309707.html

猜你在找的Android相关文章