简体   繁体   中英

how to render array of component inside Text component in react native?

I started a chat project in react native. And now I'm having a problem with showing emoji. I got data of message, extract it and save to array. This is an example of message and the array of it

abc :smile: xyz  
[
  <Text>abc </Text>,  
  <Image source={{uri:"SMILE_EMOJI_URL"}} />
  <Text> xyz</Text>
]

I will create a Text tag and put them all in as nested tags, so I just need to format one time. My expected result

<Text style={MY_STYLE}>
  <Text>abc </Text><Image source={{uri:"SMILE_EMOJI_URL"}} /><Text> xyz</Text>
</Text>

How can I do it? Thank you!

your text-Component could look like this:

class ChatMessage extends React.Component {

    constructor() {
        super();
        this.state = {
            message: ""
        }
    }

    componentWillMount() {
        var localMessage;
        for (let i = 0; i < arrayOfEmojiCodes.length; i++) {
            if (this.props.message.includes(arrayOfEmojiCodes[i])) {
                localMessage = this.props.message.split(arrayOfEmojiCodes[i])[0] + " <img src='"+arrayOfIconImages[arrayOfEmojiCodes[i]]+"' /> " + this.props.message.split(arrayOfEmojiCodes[i])[1];
                i = arrayOfEmojiCodes.length;
            } else {
                localMessage = this.props.message;
            }
        }
        this.setState({message: localMessage});
    }

    render() {
        return(
            <div className={this.props.style}>
                <p>{this.state.message}</p>
            </div>
        );
    }
}

then you can just call it:

<div className="chat">
    {['Message1 :smile', 'message2'].map((value, index) => {
        <ChatMessage key={index} message={value} />
    })}
</div>

You need to do some modification to your code to fit it your needs, but basically this should make it easier to handle the situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM