react-native - React Native 的 TextInput 如何给部分文本应用样式?

标签 react-native textinput

当用户使用 TextInput 输入文本时,我想为部分文本着色。例如,当一个单词以@开头时,我想将整个单词涂成红色。可能吗?

最佳答案

您实际上可以通过将 Text 元素嵌套在 TextInput 中来实现:

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

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

关于react-native - React Native 的 TextInput 如何给部分文本应用样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616608/

相关文章:

javascript - 我需要使用 Redux 还是 Context API

javascript - 如何根据首次启动设置初始屏幕?

android - react-native-google-signIn 没有得到 IDToken

javascript - 如何检测某些文本框是否通过外部脚本更改?

javascript - 输入字段中的背景问题

javascript - responseJson比较总是输入错误if

react-native - 类型错误 : Cannot read property 'getCurrentUserAsync' of undefined

css - 文本输入框 CSS 样式

javascript - 使用谷歌搜索 url

react-native - React Native 自定义 TextInput 对象在每个字符后失去焦点