最近开发公司的项目,做了个输入框光标位置的功能,坑挺多,抽出了时间整理了下遇到的问题,希望给大家一些帮助。
WechatIMG147.jpeg
参考官方文档
<TextInput style={styles.textInputStyle}
value={this.state.textValue}
onChangeText={(value) =>{
this.setState({textValue: value});
}}
placeholder='请输入内容'
underlineColorAndroid="transparent"
ref={t=>this.textInput=t}
/>
官方各个版本不同,会有一些输入不了的中文的bug,本人亲测,最新的57和53版本以及以前的版本,onChangeText={(value) =>{ this.setState({textValue: value});}}是没问题的,但是在53以后的新版本,这么写就不能输入中文,可以换成onChangeText={(value) =>{this.state.textValue= value}}。当然还有修改源码的解决方法,不需这么写,见此链接,不过不推荐修改源码。
下面做个例子,比如当需要添加一个【】然后光标定位在括号中间位置时,
add(){
this.textInput.focus()
let selection = this.textInput._lastNativeSelection || null;
if (!this.state.textValue){
this.setState({
textValue : this.state.textValue + "【】"
},()=>{
let position = this.state.textValue.length - 1
this.textInput.focus()
setTimeout(()=>{
this.textInput.setNativeProps({
selection : { start : position, end : position}
})
},10)
})
}else if(selection !=null && selection.start == selection.end) {
let startStr = this.state.textValue.substr(0 , selection.start)
let endStr = this.state.textValue.substr(selection.start)
this.setState({
textValue : startStr + "【】" + endStr
},()=>{
this.textInput.focus()
setTimeout(()=>{
this.textInput.setNativeProps({
selection : { start : selection.start+1 , end : selection.start+1}
})
},10)
})
} else {
this.setState({
textValue : this.state.textValue + "【】"
},()=>{
let position = this.state.textValue.length - 1
this.textInput.focus()
setTimeout(()=>{
this.textInput.setNativeProps({
selection : { start : position, end : position}
})
},10)
})
}
如果需要在对应的位置添加用【】包含的一段文字,可以这么写:
add(data){
this.textInput.focus()
let selection = this.textInput._lastNativeSelection || null;
if (!this.state.textValue){
this.setState({
textValue : this.state.textValue + `【${data}】`
},()=>{
let position = this.state.textValue.length
this.textInput.focus()
setTimeout(()=>{
this.textInput.setNativeProps({
selection : { start : position, end : position}
})
},10)
})
}else if(selection !=null && selection.start == selection.end) {
let startStr = this.state.textValue.substr(0 , selection.start)
let endStr = this.state.textValue.substr(selection.start)
this.setState({
textValue : startStr + `【${data}】` + endStr
},()=>{
this.textInput.focus()
setTimeout(()=>{
this.textInput.setNativeProps({
selection : { start : this.state.textValue.length , end : this.state.textValue.length}
})
},10)
})
} else {
this.setState({
textValue : this.state.textValue + `【${data}】`
},()=>{
let position = this.state.textValue.length
this.textInput.focus()
setTimeout(()=>{
this.textInput.setNativeProps({
selection : { start : position, end : position}
})
},10)
})
}
}