当用户在
TextInput
中输入文本时,我希望可以给一部分文本涂上颜色。例如,当一个单词以“@”开头时,我想用红色着色整个单词。这种操作是否可行?TextInput
中输入文本时,我希望可以给一部分文本涂上颜色。例如,当一个单词以“@”开头时,我想用红色着色整个单词。这种操作是否可行?您可以通过在TextInput
内部嵌套Text
元素来实现:
<TextInput onChangeText={this.handleCheckTextChange}>
<Text>{this.state.formattedText}</Text>
</TextInput>
handle函数将解析文本并为所有提及创建样式化的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});
}