React Native,在文本字符串中,更改开头带有#或@的单词的颜色,就像twitter一样

Sob*_*had 0 javascript reactjs react-native

我有一个文本字符串,其中一些单词以 # 或 @ 作为前缀(在单词开头,就像 #example 或 @example 一样)我想将这些单词更改为蓝色。反应本机

Gur*_*ran 7

您可以使用如下所示的自定义组件。

const CustomText = (props) => {
    const text = props.text.split(' ');
    return <Text>{text.map(text => {
      if (text.startsWith('@') || text.startsWith('#')) {
        return <Text style={{ color: 'blue' }}>{text} </Text>;
      }
      return `${text} `;
    })}</Text>;
}

export default function App() {
  return (
    <View style={styles.container}>
       <CustomText text="this is a @sample #text"/>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

您可以查看工作零食 https://snack.expo.io/@guruparan/demo2