代码:
TextInputComp() {
let resultArray = [];
let preIndex = 0;
for (let i = 0;i<this.state.contentInput.length;i++){
if (this.state.contentInput[i]==='@') {
if (this.state.contentInput.substring(preIndex,i)) {
resultArray.push(this.state.contentInput.substring(preIndex,i));
preIndex = i;
}
}
if (this.state.contentInput[i]===' ') {
if (this.state.contentInput.substring(preIndex,i+1)) {
resultArray.push(this.state.contentInput.substring(preIndex,i+1));
preIndex = i+1;
}
}
if (this.state.contentInput[i]==='#') {
if (this.state.contentInput.substring(preIndex,i)) {
resultArray.push(this.state.contentInput.substring(preIndex,i));
preIndex = i;
}
}
}
if (this.state.contentInput) {
if (this.state.contentInput.substring(preIndex)) {
resultArray.push(this.state.contentInput.substring(preIndex));
}
}
this.state.contentArray = resultArray;
return (
<TextInput
style={[styles.textInput, { maxHeight: px2dp(300) }]}
ref={(r) => {
this.contentInput = r;
}}
multiline={true}
textAlignVertical="top"
placeholder="分享这一刻的想法..."
placeholderTextColor="#C0BFC5"
underlineColorAndroid="transparent"
autoCapitalize={'none'}
autoComplete={'off'}
autoCorrect={false}
onEndEditing={()=>{
console.log('--onEndEditing--')
//解决iOS上文字颜色不能变化的问题,需要先加个空格,再还原
if (Platform.OS==='ios') {
let value = this.state.contentInput;
this.setState({ contentInput: value+' ' },()=>{
setTimeout(()=>{
this.setState({ contentInput: value });
},1)
});
}
}}
onChangeText={(text) => {
this.setState({ contentInput: text },()=>{
setTimeout(()=>{
this.contentInput.focus();
},1)
});
}}
onSelectionChange={(e)=>{
this.state.selection = e.nativeEvent.selection;
}}
>
{
resultArray.map((item,index)=>{
if (item[0]==='@'||item[0]==='#') {
return <Text key={'textinput_'+index} style={styles.blueText}>{item}</Text>
} else {
return <Text key={'textinput_'+index} style={styles.defaultText}>{item}</Text>
}
})
}
</TextInput>
);
}
点击添加话题或者@用户:
add(){
this.setState({ contentInput: this.state.contentInput+'#话题1'+' '},()=>{
setTimeout(()=>{
this.contentInput.focus();
},1)
});
}
网友评论