如何使用react-native-gifted-chat

时间:2019-06-05 04:29:31

标签: react-native react-native-gifted-chat

我正在开发一个移动聊天应用程序,就像一个群聊。

聊天室屏幕的左侧应为会议室所有者的评论,而右侧应为其他人的评论。

示例:用户ID 1的注释应该在聊天的左侧,用户ID 2〜100的注释应该在聊天的右侧。

我认为我应该使用renderMessage自定义聊天消息UI。但是我不知道如何有效地使用它。

我已经尝试像下面这样开发renderMessagerender

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

3 个答案:

答案 0 :(得分:0)

尝试将正在书写的用户添加到有礼功能的聊天室中:

    <GiftedChat
      isAnimated
      messages={this.props.messages}
      onSend={messages => this.onSend(messages)}
      user={{
           _id: '200',
           name: 'faisal',
      }}
      />

每条带有用户_id:'200'的消息都会显示在右侧。

将在右侧显示的消息示例:

    {
    _id: 5,
     text: 'Hello World?',
     createdAt: new Date(),
     user: {
        _id: '200',
        name: 'fasial'
      },
     },

答案 1 :(得分:0)

确保您没有将整数 (parseInt()) 值传递给 _id 字段。只需将任何整数 id 字符串化即可。邮件中的示例..

{
    _id: id.toString(),
    text: message,
    createdAt: new Date(),
    user: { _id: userId.toString(), name: name }
}

然后在 render()

isAnimated
messages={messages}
onSend={newMessages => this._onSend(newMessages)}
user={{
    _id: id.toString(),
    name: name
}}

答案 2 :(得分:-1)

renderMessages = (msg) => {
let message = msg.currentMessage
var ColorCode = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
var date = moment(message.timestamp)
.utcOffset('+05:30')
.format('hh:mm A');
console.log("single message", message)
return (
  <View>
    {/* <Text>{item.message}</Text> */}
    {message.user.user_id === this.state.login_response.id ?
      <View style={styles.left_bubble}>
        {/* <Text>{message.user.name}</Text> */}
        <Text>{message.text}</Text>
        <Text style={{alignSelf:'flex-end',color:'#8c8c8c'}}>{date}</Text>
      </View>
      :
      <View style={styles.rightBubble}>
        <Text style={{ color: ColorCode }}>{message.user.name}</Text>
        <Text style={{ padding: 2 }}>{message.text}</Text>
        <Text style={{fontSize:TextFormatter.normalize(12), alignSelf:'flex-end',color:'#8c8c8c'}}>{date}</Text>
      </View>
    }
  </View>
)}

 <GiftedChat
      messages={this.state.messages}
      onSend={Fire.shared.send}
      user={this.user}
      renderDay={this.renderDay}
      renderMessage={(message) => this.renderMessages(message)}

    />