React 天赋聊天消息对齐

React gifted chat message alignment

我无法让来自两个用户的消息在左侧和右侧对齐,同时从状态中拉出它们。他们都走在左边。如果我尝试 post 一条新消息,该消息会按预期出现在右侧,但不会在将它们从状态中拉出时出现。

示例代码

    import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { GiftedChat } from 'react-native-gifted-chat';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const [messages, setMessages] = useState([
    {
    _id: 1,
    text: 'This is a quick reply. Do you love Gifted Chat? (radio) KEEP IT',
    createdAt: new Date(),
    user: {
      _id: 2,
      name: 'React Native',
    },
  },
  {
    _id: 2,
    text: 'This is a quick reply. Do you love Gifted Chat? (checkbox)',
    createdAt: new Date(),
    user: {
      _id: 3,
      name: 'React',
    },
  }
  ]);

  const onSend = (newMessage = []) => {
    setMessages(GiftedChat.append(messages, newMessage));
  };
  
  return (
    <GiftedChat
      messages={messages}
      onSend={newMessage => onSend(newMessage)}
      user={{
        _id: 1,
      }}
    />
  );
}

此示例包含 2 条消息,均具有不同的用户 ID,但消息显示在左侧。我还在后台保存了消息,虽然写新消息不是问题,但从后台拉出来并显示它们是。

我也修改了giftedChat的renderMessage 属性,但是没有用。我使用的服务器只接受群聊,这可能是问题所在吗? 有任何想法吗?谢谢

很高兴回答这个问题 对于右对齐,一条消息在右边,一条消息在左边,你必须使用这个

  1. 使用 RenderBubble

    <GiftedChat renderBubble={this.renderBubble}. 
                isLoadingEarlier={true}/>
    
  2. 在 renderBubble 函数中,检查此条件(发件人 ID 或当前消息用户 ID)

    currentMessage.user._id == this.state.senderData.id) {
          <Bubble
               {...props}
               wrapperStyle={{
                 right: {
                   height: 200,
                   backgroundColor: 'blue',
                 },
               }}
             />
        } else {
    
    <Bubble
             {...props}
             wrapperStyle={{
               left: {
                 backgroundColor: '#f0f0f0',
               },
             }}
           />
    }
    

在这段代码中,我们区分左侧或右侧的消息