React Native中如何为TextInput部分文字应用样式?

4
当用户在TextInput中输入文本时,我希望可以给一部分文本涂上颜色。例如,当一个单词以“@”开头时,我想用红色着色整个单词。这种操作是否可行?

可以展示一个使用案例的例子吗? - Sivakumar A
2个回答

4

您可以通过在TextInput内部嵌套Text元素来实现:

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

handle函数将解析文本并为所有提及创建样式化的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

-1
你可以参考我的Expo snack。拆分单词,检查 '@' 并分别渲染每个单词,在满足条件时更改样式。

谢谢,但您正在使用<Text>,而我正在寻找一种使用<TextInput>的方法。 - ofer2980

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接