【问题标题】:How to highlight a part of a text in TextInput react native如何在TextInput中突出显示部分文本反应原生
【发布时间】:2020-07-26 19:54:21
【问题描述】:
【问题讨论】:
标签:
react-native
textinput
【解决方案1】:
这可以通过在您的TextInput 中添加Text 元素来完成:
<TextInput onChangeText={this.handleCheckTextChange}>
<Text>{this.state.formattedText}</Text>
</TextInput>
handle 函数将解析文本并为所有提及创建样式化 Text 元素,因此 formattedText 将成为 Text 元素的数组:
handleCheckTextChange = (inputText) => {
const words = inputText.split(' ');
const formattedText = [];
words.forEach((word, index) => {
const isLastWord = index === words.length - 1;
if (!word.startsWith('@')) {
return isLastWord ? formattedText.push(word) : formattedText.push(word, ' ');
}
const mention = (
<Text key={word + index} style={{color: 'red'}}>
{word}
</Text>
);
isLastWord ? formattedText.push(mention) : formattedText.push(mention, ' ');
});
this.setState({formattedText: formattedText});
}
演示:https://snack.expo.io/@raphaelmerx/text-per-word-style