当用户使用 TextInput
输入文本时,我想为部分文本着色。例如,当一个单词以@开头时,我想将整个单词涂成红色。可能吗?
最佳答案
您实际上可以通过将 Text
元素嵌套在 TextInput
中来实现:
<TextInput onChangeText={this.handleCheckTextChange}>
<Text>{this.state.formattedText}</Text>
</TextInput>
句柄函数将解析文本并为所有提及创建样式化的 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});
}
关于react-native - React Native 的 TextInput 如何给部分文本应用样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616608/