【问题标题】:Messages displayed on one side only (left hand side of the screen) - react-native-gifted-chat消息仅显示在一侧(屏幕左侧) - react-native-gifted-chat
【发布时间】:2019-01-22 13:39:26
【问题描述】:

如果有 2 个用户正在使用该应用程序,则消息将显示在屏幕左侧。无法区分它们(发送者谁发送了什么消息),只有在使用我们自己的REST Api Call to onload时才会出现,

但是当时发送一条新消息时,消息会分别显示发送方和接收方格式,另外一种情况当我当时使用twillio默认的getMessages方法时也不会出现错误。

获取两个用户的先前消息的 Twilio 方法:

this.channel.getMessages(0).then((messages) => {
    console.log("getMessages" + messages);
    this.handleBatch(messages);
});

请在上面找到截图供您参考。任何知道如何解决此问题的人或任何建议都欢迎。

【问题讨论】:

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


    【解决方案1】:

    尝试将正在写作的用户添加到giftedChat:

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

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

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

    {
      _id: 3,
      text: 'How r u?',
      createdAt: new Date(),
      user: {
        _id: 'sarathy',
        name: 'React Native'
      },
    },
    

    【讨论】:

    • 我尝试了您的解决方案,但没有奏效。我正在使用一个简单的示例,只有 2 个条目,它们都有不同的 id。您能提出其他建议吗?
    【解决方案2】:

    react-native-gifted-chat 使用用户道具区分消息,这些道具指定 用户发送消息, 所以你必须给用户道具

        <GiftedChat
                                messages={this.state.messages}
                                onSend={this.handleNewMessage.bind(this)}
                                user={{
                                    _id: your user id
                                    name: users name,
                                    avatar: users image 
                                }} 
    />
    

    如果您愿意,姓名和头像对于在有天赋的聊天中显示姓名或图像很有用

    和 onSend 事件将此用户与文本发送到 twillio 作为

    handleNewMessage = (message = {}) => {
    
                this.channel.sendMessage( message[0].text, message[0].user)
                .catch(error => console.error(error));
        }
    

    现在在您的 getMessages 上

    this.channel.getMessages(0).then((messages) => {
        console.log("getMessages" + messages);
        this.handleBatch(messages);
    });
    

    在添加有天赋的聊天之前更改消息格式作为有天赋的聊天想要 仅例如我使用状态来设置消息

    handleBatch= (message) => {
            const messageData = this.formatMessage(message);
            this.setState(previousState => ({
                messages: GiftedChat.append(previousState.messages, messageData),
            }));
        }
    
    
    
     formatMessage(message) {
    
                return {
                    _id: message.sid, // or your own unique id
                    text: message.body,
                    user: message.attributes, // here you can get your user parameters in message attributes which we send to identify user
                    createdAt: message.timestamp,
                };
            }
    
    // change above conditions as you get response by twillio.
    

    希望对你有所帮助。 如果有任何疑问,请告诉我。

    【讨论】: