【问题标题】:Display receiver messages in this.state.message在 this.state.message 中显示接收者消息
【发布时间】:2019-04-01 08:28:04
【问题描述】:

我正在使用 react-native-gifted-chat(https://github.com/FaridSafi/react-native-gifted-chat) 在我的应用程序上创建聊天界面,我想从我的数据库中加载消息,但是如何在 react-native-gifted-chat 中指定它接收者发送消息而不是发送者,即在应用加载之前,消息被加载到this.state.messages,根据文档,应该是这样的

 {
 _id: 1,
 text: 'My message',
 createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
 user: {
 _id: 2,
 name: 'React Native',
 avatar: 'https://facebook.github.io/react/img/logo_og.png',
 },
 image: 'https://facebook.github.io/react/img/logo_og.png',
 // Any additional custom parameters are passed through
 }

文档只说明了如何指定发送者的消息,没有说明接收者,请问如何显示接收者的消息,即

  {
  _id: 2,
  text: 'Receiver's message',
  createdAt: new Date(Date.UTC(2016, 6, 11, 17, 20, 0)),
  user: {
   _id: 2,
  name: 'Receiver',
  avatar: 'https://facebook.github.io/react/img/logo_o3.png',
  },
  image: 'https://facebook.github.io/react/img/logo_o3.png',
  }

【问题讨论】:

  • 消息对象的“user”键中的键“_id”应该不同。

标签: android reactjs react-native state


【解决方案1】:

https://github.com/FaridSafi/react-native-gifted-chat/blob/master/example/App.js 中有一个例子,你可以在那里看到一个 onReceive() 函数。

 onReceive(text) {
    this.setState((previousState) => {
      return {
        messages: GiftedChat.append(previousState.messages, {
          _id: Math.round(Math.random() * 1000000),
          text: text,
          createdAt: new Date(),
          user: {
            _id: 2,
            name: 'React Native',
            // avatar: 'https://facebook.github.io/react/img/logo_og.png',
          },
        }),
      };
    });
  }

你可以在收到消息时像这样触发这个函数。(当状态改变时)

【讨论】:

    【解决方案2】:

    您可以通过向 GiftedChat 组件添加属性来指定活动用户:

    <GiftedChat
            messages={this.state.messages}
            onSend={messages => this.onSend(messages)}
            user={{
              _id: 1,
            }}
          />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      相关资源
      最近更新 更多