RN--聊天组件 react-native-gifted-chat 学习

祁修平
2023-12-01

一.  

import React, { Component } from 'react';
import { Platform } from 'react-native';
import PropTypes from 'prop-types';
import { GiftedChat } from 'react-native-gifted-chat';
import emojiUtils from 'emoji-utils';
import { createStackNavigator, createAppContainer } from "react-navigation";

import SlackMessage from './SlackMessage';

export default class App extends React.Component {
  state = {
    messages: [],
  }

  //  渲染前
  componentWillMount() {
    this.setState({
      messages: [
        {
          _id: 1,     //消息的ID,用于标示,必须唯一
          text: 'Hello developer',  
          createdAt: new Date(),    //发送的时间
          user: {
            _id: 2,        //发送方的ID 如果是自己的ID 则在右边,否则在左边
            name: 'React Native',
            avatar: 'https://placeimg.com/140/140/any',
          },
        },
      ],
    })
  }

  //点击send时的回调
  onSend(messages = []) {
    this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }))
  }
  // 自定义消息的内容View
  renderMessage(props) {
    const { currentMessage: { text: currText } } = props;

    let messageTextStyle;

    // Make "pure emoji" messages much bigger than plain text.
    if (currText && emojiUtils.isPureEmojiString(currText)) {
      messageTextStyle = {
        fontSize: 28,
        // Emoji get clipped if lineHeight isn't increased; make it consistent across platforms.
        lineHeight: Platform.OS === 'android' ? 34 : 30,
      };
    }

    return (
      <SlackMessage {...props} messageTextStyle={messageTextStyle} />
    );
  }


    //  自定义气泡
     _renderBubble(props) {
    return (
      <Bubble
        {...props}
        wrapperStyle={{
          left: { //对方的气泡
            backgroundColor: '#F5F7F7',
          },
          right:{ //我方的气泡
            backgroundColor:'#FFF5EE'
          }
        }}
      />
    );
  }

  //  最终渲染
  render() {
    return (
      <GiftedChat
        messages={this.state.messages}   // 点击send时这个state的message作为参数加到previousstate的message里
         //点击send时的回调
        onSend={messages => this.onSend(messages)}
        //  定义用户的id 如果消息消息的发送方的id和此id相同,则显示在右边
        user={{
          _id: 1,
        }}
        // 有这条则返回自定义的,否则使用系统默认
       // renderMessage={this.renderMessage}
        
        //是否展示自己的头像,默认时false 只展示别人的头像
        showUserAvatar
        //renderAvatarOnTop(Bool) 头像显示在顶部还是底部,默认是底部
        renderAvatarOnTop
        // 自定义气泡
        renderBubble={this._renderBubble}
      />
    );
  }

}


 

 类似资料: