admin管理员组

文章数量:1426913

I have a text string some of words are having # or @ as prefix (in start of words, just as #example or @example) i want to change such words into blue color . React Native

I have a text string some of words are having # or @ as prefix (in start of words, just as #example or @example) i want to change such words into blue color . React Native

Share Improve this question asked May 14, 2020 at 12:49 Soban ArshadSoban Arshad 1,43120 silver badges17 bronze badges 3
  • please share your code – Asad Commented May 14, 2020 at 12:53
  • just make them into anchor tags. – Michael Commented May 14, 2020 at 12:55
  • 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> ); } – Soban Arshad Commented Jan 23, 2021 at 10:49
Add a ment  | 

2 Answers 2

Reset to default 7

You can use a custom ponent like below.

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

You can check the working snack https://snack.expo.io/@guruparan/demo2

This is my solution for this problem:

const changeColorInText = useMemo(() => {
        const textWithQuote = text.split("'")[1];
        const textParsed: string[] = text.split(textWithQuote);
        return (
            <>
                <Text>{textParsed[0]}</Text>
                <Text
                    style={{
                        color: 'red',
                        fontWeight: 'bold',
                    }}>
                    {textWithQuote}
                </Text>
                <Text>{textParsed[1]}</Text>
            </>
        );
    }, [text]);

I think will help for maybe different scenarios

本文标签: