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

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

获取和设置react native 的TextInput的光标_第1张图片

 

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

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

获取和设置react native 的TextInput的光标_第2张图片

使用方法:

 this.setState({keywords})}
    value={this.state.keywords}
/>



 this.addSymbol('keywords', '+')}>+



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

 

 

你可能感兴趣的:(react,native)