我正在开发一个移动聊天应用程序,这就像一个群聊。
房主的评论应该在聊天界面的左边,其他人的评论应该在右边。
示例:用户 id 1 的评论应该在聊天的左侧,用户 id 2~100 的评论应该在聊天的右侧。
我想我应该使用renderMessage
自定义聊天消息 UI。但我不明白如何有效地使用它。
我已经尝试过开发renderMessage
并render
喜欢下面的内容。
import React, { Component } from 'react';
import { Image, ImageBackground, Text, Linking, SafeAreaView, ScrollView, StyleSheet, View } from 'react-native';
import { Body, Container, Header, Icon, Left, Right, Thumbnail } from "native-base";
import { Button, List } from 'react-native-paper';
import { GiftedChat, Composer } from 'react-native-gifted-chat';
export default class ChatScreen extends Component {
messages = [
{
_id: 4,
text: <Text onPress={() => ( alert('Hello'))} style={{ color: 'red' }}>Sample</Text>,
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
user: {
_id: 1,
name: 'Chat owner'
}
},
{
_id: 3,
text: <Text onPress={() => ( alert('Hello'))} style={{ color: 'red' }}>Sample</Text>,
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
system: true,
// Any additional custom parameters are passed through
},
{
_id: 2,
text: <Text onPress={() => { alert('hello')}} style={{ color: 'red' }}>Sample</Text>,
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
system: true,
// Any additional custom parameters are passed through
},
{
_id: 1,
text: 'This is a quick reply. Do you love Gifted Chat? (radio) KEEP IT',
createdAt: new Date(),
user: {
_id: 2,
name: 'Chat user',
},
},
];
renderComposer = props => {
return (
<View style={{flexDirection: 'row'}}>
<Icon type='SimpleLineIcons' name='paper-clip' style={{ fontSize: 20, justifyContent: 'center', paddingTop: 10, paddingLeft: 8 }}/>
<Composer {...props} />
<Button>Submit</Button>
</View>
);
};
renderMessage = props => {
return (
<View style={{ paddingLeft: 10 }} >
<Thumbnail small source={require('../../assets/thumbnail.png')} style={{ justifyContent: 'center' }}/>
</View>
);
};
onSend = (messages = []) => {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
};
render() {
return (
<Container>
<GiftedChat
renderComposer={this.renderComposer}
renderMessage={this.renderMessage}
onSend={(messages) => this.onSend(messages)}
messages={this.messages}
placeholder=''
loadEarlier={true}
showAvatarForEveryMessage={true}
renderUsernameOnMessage={true}
/>
</Container>
)
}
}
现在,所有消息都在聊天的左侧,如下所示。
https://gyazo.com/bfe08a8f648f3d4648a8d6d26556b116
当然,聊天中的所有消息都在左侧,因为Thumbnail
是放在左侧的。我想知道如何从“renderMessage”中的消息中获取用户 ID。如果我知道,我将开发如下代码。
renderMessage = props => {
paddingLeft = (userId === 1 ? '10' : '200') // I will add this code
return (
<View style={{ paddingLeft: paddingLeft }} >
<Thumbnail small source={require('../../assets/thumbnail.png')} style={{ justifyContent: 'center' }}/>
</View>
);
};