我想通过更改文本的背景颜色在React Native应用程序中突出显示多行文本。问题在于背景颜色在整个文本区域中变化,而不仅仅是在单词下方。
class Example extends Component {
render() {
const text = '...';
return (
<View style={styles.textContainer}>
<Text style={styles.textStyle}>
{text}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
textContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
width: 200,
},
textStyle: {
backgroundColor: 'red',
},
});
Run Code Online (Sandbox Code Playgroud)
上面的代码导致如下所示:
但我希望它看起来像这样:
我可以通过拆分文本并将背景颜色添加到各个单词来获得该结果:
class Example extends Component {
render() {
const text = '...';
const brokenText = text.split(' ').map(word => (
<Text style={styles.textStyle}>{word} </Text>
));
return (
<View style={styles.textContainer}>
{brokenText}
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
但是将文本分割成单个单词似乎不是最好的解决方案,并且会带来巨大的性能损失。有没有更清洁的方法?