获取和设置react native 的TextInput的光标

需求:通过按键向TextInput中输入特定字符。如图所示。

 

问题:如何把字符插入到光标所在位置,就需要获取光标位置

打印   this.refs.keywords可以找到:

函数:setNativeProps用于设置光标位置。传参为{selection : { start : start, end : end}},指定光标的开始和结束。如果start和end不能这说明start->end位置的内容为选中状态。this.refs[type].setNativeProps({selection : { start : start, end : end}})

属性:_lastNativeSelection是个对象,包含光标的开始和结束位置。{start:start end: end}

使用方法:

<TextInput
    ref={"keywords"}
    style={styles.textInputKeyword}
    multiline={true}
    numberOfLines={4}
    maxLength={200}
    placeholder={'请输入事件关键词'}
    placeholderTextColor={'#B2B2B2'}
    onChangeText={(keywords) => this.setState({keywords})}
    value={this.state.keywords}
/>



<Text style={styles.buttonSymbolText}  
     onPress={() => this.addSymbol('keywords', '+')}>+</Text>



addSymbol = (type, symbol) => {
        if (this.state[type].length < 200) {
            this.refs[type].focus();
            let selection = this.refs[type]._lastNativeSelection || null;
            let obj = {};
            obj[type] = selection ?
                this.state[type].substr(0, selection.start) + symbol + this.state[type].substr(selection.end) :
                this.state[type] + symbol;
            this.setState({...obj}, () => {
                this.refs[type].focus();
                setTimeout(()=>{
                    this.refs[type].setNativeProps({
                        selection : { start : selection.start+1, end : selection.start+1}
                    })
                })
            });
        }
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值