【问题标题】:How to highlight a part of a text in TextInput react native如何在TextInput中突出显示部分文本反应原生
【发布时间】:2020-07-26 19:54:21
【问题描述】:

在我的 <TextInput> 中,我必须为每个以“@”开头的单词设置背景颜色。我可以检测到“@”,但我从未见过突出显示部分文本的文档。 不是所有的文字,只是一部分。

我不想在另一个 <View><Text> 中看到我的文字,如本例所示:https://gist.github.com/scf4/012e9f615f6b43a1712a083b162afd94

我不知道我们是否真的有解决方案,但如果你有的话,非常感谢。

【问题讨论】:

标签: react-native textinput


【解决方案1】:

这可以通过在您的TextInput 中添加Text 元素来完成:

<TextInput onChangeText={this.handleCheckTextChange}>
  <Text>{this.state.formattedText}</Text>
</TextInput>

handle 函数将解析文本并为所有提及创建样式化 Text 元素,因此 formattedText 将成为 Text 元素的数组:

  handleCheckTextChange = (inputText) => {
    const words = inputText.split(' ');
    const formattedText = [];
    words.forEach((word, index) => {
      const isLastWord = index === words.length - 1;
      if (!word.startsWith('@')) {
        return isLastWord ? formattedText.push(word) : formattedText.push(word, ' ');
      }
      const mention = (
        <Text key={word + index} style={{color: 'red'}}>
          {word}
        </Text>
      );
      isLastWord ? formattedText.push(mention) : formattedText.push(mention, ' ');
    });
    this.setState({formattedText: formattedText});
  }

演示:https://snack.expo.io/@raphaelmerx/text-per-word-style

【讨论】:

    猜你喜欢
    • 2018-07-21
    • 2019-10-14
    • 2013-12-29
    • 2012-05-14
    • 2018-02-26
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    相关资源
    最近更新 更多