React Native - 设置TextInput游标位置 [英] React Native - Setting TextInput cursor position

查看:865
本文介绍了React Native - 设置TextInput游标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有没有人成功完成?

谢谢。

推荐答案

As @ this.lau_表示有一个名为 selection 的控制器属性,它接受一个带有键开头和结尾的对象。

As @this.lau_ says there is a controller property called selection which accepts an object with keys start and 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 ,如下所示:

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

示例:

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

这篇关于React Native - 设置TextInput游标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆