需求:通过按键向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}
})
})
});
}
}