如何在React Native中正确突出显示文本? [英] How to properly highlight text in React Native?

查看:163
本文介绍了如何在React Native中正确突出显示文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过更改文本的背景颜色在React Native应用程序中突出显示多行文本.问题在于背景颜色在整个文本区域中变化,而不仅仅是在单词下方.

I would like to highlight a multiline text in a React Native app by changing the text's background color. The problem is that the background color changes in the whole text area, not just under the words.

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

上面的代码导致如下所示:

The code above results in something that looks like this:

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

But I would like it to look like this:

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

I can get that result by splitting the text and adding the background color to the individual words:

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

但是将文本分割成单个单词似乎不是最好的解决方案,并且具有巨大的性能成本.有没有更清洁的方法?

But splitting the text into individual words doesn't seem like the best solution, and has a huge performance cost. Is there any cleaner way to do it?

推荐答案

这仍然不正确,但是我按照您的期望通过在每个单词之间添加一个不可见的字符(此处为无宽度空格)来呈现它,因此文本中断了在它上面没有背景色.这是代码:

This is still not proper but I had it rendering as you expect by adding an invisible character (no-width space here) between each word, so the text breaks on it which has no background color. Here is the code :

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

这是一个小吃,您可以在其中查看结果并进行操作: 它肯定可以改进,我很乐意获得反馈.

It can surely be improved, I'll be happy to have feedback.

这篇关于如何在React Native中正确突出显示文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆