【问题标题】:React gifted chat message alignmentReact 有天赋的聊天消息对齐
【发布时间】:2021-01-06 05:46:33
【问题描述】:

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

示例代码

    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属性,但无济于事。我正在使用仅接受群聊的服务器,这可能是问题吗? 有任何想法吗?谢谢

【问题讨论】:

    标签: reactjs react-native alignment messagebox react-native-gifted-chat


    【解决方案1】:

    很高兴回答这个问题 对于右对齐,右侧有一条消息,左侧有一条消息,您必须使用此

    1. 使用渲染气泡

      <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',
                 },
               }}
             />
      }
      

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

    【讨论】:

    • 您好,感谢您的回答,我尝试了您的解决方案,但没有奏效。我还尝试在没有任何条件的情况下使用 仍然无法正常工作,(请参阅此链接amanhimself.dev/blog/chat-app-with-react-native-part-4)。是不是我做错了什么?
    • 在玩了 之后,我找到了属性 Position,它使我能够对齐消息。谢谢
    • 亲爱的,如果 id 相等,您必须检查两条消息的 id,然后右侧的气泡将呈现在右侧.. 如果 id 不相等,这将表明正确的消息是您的如果您仍然遇到问题,它将在左侧尝试这个,然后您可以在小吃博览会上分享您的代码,这里是 url = snack.expo.io
    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2022-11-15
    • 2018-01-14
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多