当用户使用输入文本时,我想给文本加上颜色TextInput
。例如,当一个单词以@开头时,我想用红色为整个单词涂上颜色。可能吗?
您实际上可以通过将Text
元素嵌套在中来实现TextInput
:
<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});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句