在this.state.message中显示接收者消息

时间:2018-10-28 02:57:41

标签: android reactjs react-native state

我正在使用react-native-gifted-chat(https://github.com/FaridSafi/react-native-gifted-chat)在我的应用上创建聊天界面,我想从数据库中加载消息,但是如何在react-native-gifted中指定它-聊天说接收者发送的不是消息,即发送者,即在应用加载之前,根据文档说明,消息已加载到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',
  }

2 个答案:

答案 0 :(得分:0)

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

您可以在接收消息时触发此功能。(状态更改时)

答案 1 :(得分:0)

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

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