Bru*_*ger 9 javascript android ios flexbox 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',
},
});
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)
但是将文本分割成单个单词似乎不是最好的解决方案,并且会带来巨大的性能损失。有没有更清洁的方法?
这仍然不正确,但我通过在每个单词之间添加不可见字符(此处为无宽度空格)来按照您的预期进行渲染,因此文本会在没有背景颜色的情况下中断。这是代码:
\n\nconst NO_WIDTH_SPACE = \'\xe2\x80\x8b\'; // This is a special char you should copy and paste, not an empty string!\n\nconst Example = () => {\n const highlight = string =>\n string.split(\' \').map((word, i) => (\n <Text key={i}>\n <Text style={styles.highlighted}>{word} </Text>\n {NO_WIDTH_SPACE}\n </Text>\n ));\n\n return (\n <Text>\n Some regular text {highlight(\'with some properly highlighted text\')}\n </Text>\n );\n}\n\nconst styles = StyleSheet.create({\n highlighted: {\n backgroundColor: \'yellow\',\n },\n});\nRun Code Online (Sandbox Code Playgroud)\n\n这是一个 Snack,您可以在其中查看结果并使用它: https ://snack.expo.io/@adesurirey/properly-highlight-text-with-react-native \n
它肯定可以改进,我很高兴收到反馈。
\n小智 -3
我相信问题出display在你的组件的 css 属性上。
您的组件似乎正在渲染display: block;而不是display: inline;
请参阅示例:https ://jsfiddle.net/oorangecchicken/2qkey6o9/
| 归档时间: |
|
| 查看次数: |
3078 次 |
| 最近记录: |