gpt4 book ai didi

javascript - 如何在 React Native 中正确突出显示文本?

转载 作者:可可西里 更新时间:2023-11-01 03:19:07 26 4
gpt4 key购买 nike

我想通过更改文本的背景颜色来突出显示 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',
},
});

上面的代码产生如下所示的结果:current output

但我希望它看起来像这样:expected output

我可以通过拆分文本并为单个单词添加背景颜色来获得该结果:

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>
);
}
}

但将文本拆分为单个单词似乎并不是最佳解决方案,而且会产生巨大的性能成本。有更清洁的方法吗?

最佳答案

这仍然不正确,但我通过在每个单词之间添加一个不可见的字符(这里没有宽度空格)来按照您的预期进行渲染,因此文本在没有背景颜色的情况下中断。这是代码:

const NO_WIDTH_SPACE = '​'; // This is a special char you should copy and paste, not an empty string!

const Example = () => {
const highlight = string =>
string.split(' ').map((word, i) => (
<Text key={i}>
<Text style={styles.highlighted}>{word} </Text>
{NO_WIDTH_SPACE}
</Text>
));

return (
<Text>
Some regular text {highlight('with some properly highlighted text')}
</Text>
);
}

const styles = StyleSheet.create({
highlighted: {
backgroundColor: 'yellow',
},
});

这是一个 Snack,您可以在其中查看结果并使用它: https://snack.expo.io/@adesurirey/properly-highlight-text-with-react-native Snack preview

肯定可以改进,我很乐意提供反馈。

关于javascript - 如何在 React Native 中正确突出显示文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com