格式
我们用##代表一个话题,输入框内在任意位置输入##就可以嵌入话题
效果图
实现逻辑
主要是解决输入框变色问题,这里用一个Text组件盖在输入框上面,输入框默认颜色设为透明
下面贴上代码
<Text style={{ fontSize: 18, color: '#000', marginTop: 100 }}>输入话题试试看吧(##)</Text>
<View
style={{
backgroundColor: 'green',
width: '100%',
height: 100
}}
>
<TextInput
maxLength={100}
value={this.state.value}
onChangeText={v => {
let value = v
if (value.length > this.state.value.length) {
// 写入
let lastStr = value.substr(v.length - 1)
// console.log('lastStr = ', lastStr);
if (lastStr === '#') {
let count = getCharCount(v, '#')
// console.log('#的次数 = ', count);
// 判断#是一对儿的第二个
if (count > 1 && count % 2 === 0) {
// 一对儿的第一个位置
let firstIndex = findCharIndex(v, '#', count - 1)
// console.log('firstIndex = ', firstIndex);
if (firstIndex !== -1) {
let frontStr = value.substring(0, firstIndex)
// console.log('frontStr = ', frontStr);
let behindStr = value.substr(firstIndex)
// console.log('behindStr = ', behindStr);
value = frontStr + ' ' + behindStr + ' '
}
}
}
}
this.setState({
value: value
})
}}
multiline={true}
numberOfLines={5}
style={{
backgroundColor: 'white',
height: 100,
fontSize: 16,
paddingHorizontal: 10,
paddingTop: 10,
textAlignVertical: 'top',
color: 'transparent'
}}
/>
{this.getTheme()}
</View>
输入框的显示逻辑
getTheme() {
let list = this.state.value.split('#')
let listView = []
// console.log('list = ',this.state.value, list)
for (let index = 0; index < list.length; index++) {
const element = list[index]
if (index % 2 === 0) {
listView.push(<Text>{element}</Text>)
} else if (index % 2 === 1 && index === list.length - 1) {
listView.push(<Text>{'#' + element}</Text>)
} else {
listView.push(<Text style={{ color: 'orange' }}>{'#' + element + '#'}</Text>)
}
}
return (
<Text
style={{
position: 'absolute',
top: 0,
left: 0,
marginHorizontal: 10,
fontSize: 16,
marginTop: 10
// backgroundColor: 'red'
}}
>
{listView.map(item => item)}
{/* <Text>{this.state.value}</Text> */}
</Text>
)
}
两个字符串处理方法
// 字符串中指定字符指定出现第num次的位置
export function findCharIndex(str: string, char, num: number) {
let x = -1
for (var i = 0; i < num; i++) {
x = str.indexOf(char, x + 1)
}
return x
}
// 判断字符串是否包含某些字符串
export function checkChatIsValid(chatText: String, rule?) {
let ruleArray = rule ? rule : config.chatTextRule
let realText = chatText.replace(/\s*/g, '').toLowerCase() // 去除所有空格转小写
if (ruleArray && ruleArray.length > 0) {
for (let i = 0; i < ruleArray.length; i++) {
if (realText.includes(ruleArray[i])) {
return false
}
}
}
return true
}