我想通過更改文本的背景色來突出顯示React Native應用程序中的多行文本。問題在於背景顏色在整個文本區域中變化,而不僅僅是在文字之下。如何在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',
},
});
,看起來像這樣上面的東西結果代碼:
,但我想它是這樣的:
我可以通過拆分文本並添加得到這一結果背景顏色的單個字:
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>
);
}
}
但是將文本分割成單個單詞似乎並不是最好的解決方案並且具有巨大的性能成本。有沒有更乾淨的方法來做到這一點?
你試過使用類似文字陰影的東西嗎?我不確定什麼反應原生等價物會是 – Felipe
@Felipe textShadow具有不同的外觀(它是文本下的模糊陰影),並且對於突出顯示文本不太有效:/ –
是真的,我想也許用一些黑客的用法,但它沒有奏效。怎麼樣,如果你分裂新行而不是字符,類似於此https://stackoverflow.com/questions/16597304/background-color-for-text-only – Felipe