天天看點

reactnative在文本框光标處插入文字的實作方法

效果展示:

reactnative在文本框光标處插入文字的實作方法

注意:如果使用了scroll滾動插件,需要使用keyboardShouldPersistTaps="always"方法防止鍵盤阻止按鈕被觸發,上篇文章有介紹:

https://blog.csdn.net/ywl570717586/article/details/102505241

render中的簡略代碼:

render () {
	const listItems = this.state.pianyuList.map((item,index) =>
		<TouchableOpacity 
		key={index}
		onPress={() => this.insertString('', item.TemplateName)}>
			<Text>{item.TemplateName}</Text>
		</TouchableOpacity>
	);
	return (
		<View>
			<KeyboardAwareScrollView style={{flex: 1}} keyboardShouldPersistTaps="always">
				<View style={{}}>
					<TextInput 
					ref={"FindingsDescribe"} 
					placeholder="請輸入會診描述" 
					multiline = {true} 
					underlineColorAndroid="transparent"
					onChangeText={(FindingsDescribe) => this.setState({FindingsDescribe})}
					value={this.state.FindingsDescribe}
					></TextInput>
				</View>
				<View>
					<TextInput 
					ref={"Conclusion"} 
					underlineColorAndroid="transparent"
					onChangeText={(Conclusion) => this.setState({Conclusion})}
					placeholder="請輸入會診結論" 
					multiline = {true} 
					value={this.state.Conclusion}
					></TextInput>
				</View>
				<View>
					<Text}}>快速錄入</Text>
					<View>
						{listItems}
					</View>
				</View>
			</KeyboardAwareScrollView>
		</View>
	);
}
           

邏輯代碼:

insertString (type, symbol) {
	// 擷取光标所在的textinput的ref,可實作在光标出添加文字
	if(this.refs.FindingsDescribe.isFocused()){
		type = "FindingsDescribe"
	}
	else if(this.refs.Conclusion.isFocused()){
		type = "Conclusion"
	} else {
		return;
	}
	// _lastNativeSelection:光标所在位置,若未初始化,則指派為{start: 0, end: 0}
	let selection = this.refs[type]._lastNativeSelection || {start: 0, end: 0};
	let obj = {};
	// 在光标位置處插入文字
	obj[type] = this.state[type].substr(0, selection.start) + symbol + this.state[type].substr(selection.end);
	// 插入完成後把光标位置後移到恰當位置
	this.setState({...obj}, () => {
		setTimeout(()=>{
			this.refs[type].setNativeProps({
				selection : { start : selection.start+symbol.length, end : selection.start+symbol.length}
			})
		})
	});
}
           

這樣就可以實作需求了,注意有個地方寫法有兩種,作用是一樣的:

<TextInput 
ref={"FindingsDescribe"} 
placeholder="請輸入會診描述" 
multiline = {true} 
underlineColorAndroid="transparent"
onChangeText={(FindingsDescribe) => this.setState({FindingsDescribe})}
value={this.state.FindingsDescribe}
></TextInput>
           
<TextInput 
ref={component => this.FindingsDescribeRef = component}
placeholder="請輸入會診描述" 
multiline = {true} 
underlineColorAndroid="transparent"
onChangeText={(FindingsDescribe) => this.setState({FindingsDescribe})}
value={this.state.FindingsDescribe}
></TextInput>
           

這兩種方式差別在于調用時的寫法會有不同:

// 第一種調用方法
this.refs[type]._lastNativeSelection
// 第二種調用方法
this.FindingsDescribeRef._lastNativeSelection
           

完成。