React Native Gifted Chat 全功能接入与深度定制指南

React Native Gifted Chat 全功能接入与深度定制指南

【免费下载链接】react-native-gifted-chat 💬 The most complete chat UI for React Native 【免费下载链接】react-native-gifted-chat 项目地址: https://gitcode.com/gh_mirrors/re/react-native-gifted-chat

导读:本文以 react-native-gifted-chat 官方 README 为主线,系统讲解这个 React Native 聊天 UI 库的完整接入流程:从环境要求、Expo / 裸 RN 项目的安装配置,到消息数据模型、全量 Props 参考、回复、表情反应、链接解析、消息状态等高级特性的实战用法。同时结合仓库源码(src/ 目录)与示例应用(example/ 目录)进行纵深验证,帮助读者在阅读后能够独立搭建一个可运行、可深度定制的聊天界面,并理解各配置项背后的实现原理。

项目概述与定位

react-native-gifted-chat 是目前 React Native 生态中功能最完整的聊天 UI 库之一,同时支持 iOS、Android 与 Web(react-native-web),并内置完整的 TypeScript 类型定义,与 Expo 兼容。官方将自身定位为 "The most complete chat UI for React Native & Web"。

它提供的开箱即用能力包括:

  • 🎨 完全可定制:几乎所有组件都可以通过 renderXxx 系列 Props 替换为自己的实现;
  • 📎 Composer Actions:在输入工具栏左侧附加图片、文件或自定义操作按钮;
  • ↩️ 回复消息:滑动消息触发回复,带回复预览与消息引用(线程)效果;
  • ⏮️ 加载更早消息:无限滚动与分页支持;
  • 📋 复制到剪贴板:长按消息弹出复制操作;
  • 🔗 智能链接解析:自动识别 URL、邮箱、电话、话题标签(hashtag)与 @ 提及(mention);
  • 👤 头像:支持用户首字母或自定义头像图片;
  • 🌍 本地化日期:基于 Day.js 的完整 i18n 支持;
  • ⌨️ 键盘处理:基于 react-native-keyboard-controller 的跨平台智能避让;
  • 💬 系统消息:在聊天流中插入系统通知;
  • ⚡ 快捷回复:机器人风格的快捷回复按钮;
  • 😀 表情反应:长按消息添加 emoji 反应,支持反应药丸与可选的全量表情浏览器;
  • ✍️ 正在输入指示器:展示对方正在输入的状态;
  • ✅ 消息状态:已发送 / 已送达 / 已读勾选标记;
  • ⬇️ 回到底部按钮:快速回到最新消息;
  • 🌐 Web 支持:与 react-native-web 配合使用;
  • 📱 Expo 支持:与 Expo SDK 50+ 无缝集成;
  • 📝 TypeScript:随库发布完整类型定义。

⚠️ 维护状态说明:根据 README 顶部的说明,本包目前已进入 维护模式(maintenance mode),不再接收新特性。开发工作已迁移到一个维护中的 fork(@kesha-antonov/react-native-chat),新项目被建议优先使用该 fork,迁移成本主要是包名替换(fork 中提供迁移指南)。对于既有项目,本仓库仍持续获得修复与维护,可放心继续使用。

环境要求(Requirements)

在安装前,请确认项目满足以下版本要求:

依赖项最低版本要求
React Native>= 0.70.0
iOS>= 13.4
AndroidAPI 21+(Android 5.0)
ExpoSDK 50+
TypeScript>= 5.0(可选)

安装指南

react-native-gifted-chat 有四个必需的运行时依赖,其中 react-native-reanimated 与 react-native-gesture-handler 承担滑动回复、表情反应选择器等动画与手势能力,react-native-safe-area-context 提供安全区 insets,react-native-keyboard-controller 负责键盘避让。

Expo 项目

npx expo install react-native-gifted-chat react-native-reanimated react-native-gesture-handler react-native-safe-area-context react-native-keyboard-controller

npx expo install 会自动选取与当前 Expo SDK 兼容的版本,是 Expo 项目最稳妥的安装方式。

裸 React Native 项目

Step 1:安装依赖包

使用 yarn:

yarn add react-native-gifted-chat react-native-reanimated react-native-gesture-handler react-native-safe-area-context react-native-keyboard-controller

使用 npm:

npm install --save react-native-gifted-chat react-native-reanimated react-native-gesture-handler react-native-safe-area-context react-native-keyboard-controller

Step 2:安装 iOS Pods

npx pod-install

Step 3:配置 react-native-reanimated

按照 react-native-reanimated 官方安装指南,在 Babel 配置中(babel.config.cjs)添加其 Babel 插件:

module.exports = {
  presets: ['babel-preset-expo'],
  plugins: ['react-native-reanimated/plugin'],
}

注意:Reanimated 的 Babel 插件必须放在插件列表的最后一位。

快速开始:最小可用聊天界面

安装完成后,下面的代码即可渲染一个功能完整的聊天界面:

import React, { useState, useCallback, useEffect } from 'react'
import { GiftedChat } from 'react-native-gifted-chat'
import { useHeaderHeight } from '@react-navigation/elements'

export function Example() {
  const [messages, setMessages] = useState([])

  // keyboardVerticalOffset = 从屏幕顶部到 GiftedChat 容器的距离
  // useHeaderHeight() 返回状态栏 + 导航栏高度之和
  const headerHeight = useHeaderHeight()

  useEffect(() => {
    setMessages([
      {
        _id: 1,
        text: 'Hello developer',
        createdAt: new Date(),
        user: {
          _id: 2,
          name: 'John Doe',
          avatar: 'https://placeimg.com/140/140/any',
        },
      },
    ])
  }, [])

  const onSend = useCallback((messages = []) => {
    setMessages(previousMessages =>
      GiftedChat.append(previousMessages, messages),
    )
  }, [])

  return (
    <GiftedChat
      messages={messages}
      onSend={messages => onSend(messages)}
      user={{
        _id: 1,
      }}
      keyboardAvoidingViewProps={{ keyboardVerticalOffset: headerHeight }}
    />
  )
}

💡 提示:仓库的 example 目录下有更多完整示例,包括 Slack 风格消息、快捷回复、自定义组件等,可直接作为开发参考。

GiftedChat.append(previousMessages, messages) 是一个静态工具方法,负责把新消息插入到消息数组的前端(因为列表默认采用倒序渲染,isInverted 默认 true)。

消息数据模型(Data Structure)

消息、系统消息与快捷回复的数据结构统一由 src/Models.ts 定义。完整的消息对象结构如下:

interface IMessage {
  _id: string | number
  text: string
  createdAt: Date | number
  user: User
  image?: string
  video?: string
  audio?: string
  system?: boolean
  sent?: boolean
  received?: boolean
  pending?: boolean
  quickReplies?: QuickReplies
}

interface User {
  _id: string | number
  name?: string
  avatar?: string | number | (() => React.ReactNode)
}

对照 src/Models.ts 的源码,IMessage 还包含以下可选高级字段(README 中亦有相应章节展开):

  • replyMessage?: ReplyMessage:消息引用的被回复消息(_id、text、user、audio、image 五个字段,见 src/Models.ts);
  • reactions?: MessageReaction[]:消息上的表情反应,结构为 { emoji: string, userIds: (string | number)[] }(见 src/Models.ts);
  • location?: { latitude, longitude }:消息附带的地理位置。

快捷回复(QuickReplies)的结构为:

interface QuickReplies {
  type: 'radio' | 'checkbox'
  values: Reply[]
  keepIt?: boolean
}

Props 参考:全量配置速查

所有 Props 的 TypeScript 签名定义在 src/GiftedChat/types.ts 中,GiftedChat 组件本身是泛型组件(GiftedChat<TMessage extends IMessage>),下文按模块分组介绍。

核心配置(Core Configuration)

Prop类型说明
messagesArray要展示的消息数组
userObject当前发送消息的用户:{ _id, name, avatar }
onSendFunction发送消息时的回调
messageIdGeneratorFunction为新消息生成 id。默认是一个简单随机字符串生成器
localeString日期本地化语言。使用前需先导入对应 locale,如 require('dayjs/locale/de') 或 import 'dayjs/locale/fr'
colorScheme'light' | 'dark'强制明/暗色模式。设置后覆盖系统配色;undefined 时跟随系统。默认 undefined

关于 messageIdGenerator 的默认实现,src/GiftedChat/index.tsx 中可以看到源码使用的是 (Math.random() + 1).toString(36).substring(7),并注释说明:刻意不引入 uuid,以避免额外增加原生依赖;库的使用者可以自行传入任意算法(如基于数据库自增 id 或 UUID)覆盖。locale 默认值为 'en'。

Refs

Prop类型说明
messagesContainerRefFlatList ref指向消息列表的 ref
textInputRefTextInput ref指向文本输入框的 ref

键盘与布局(Keyboard & Layout)

Prop类型说明
keyboardProviderPropsObject透传给 KeyboardProvider 的 Props。默认值:statusBarTranslucent: true(Android 状态栏半透明 / edge-to-edge 模式下正确计算键盘高度所必需)、navigationBarTranslucent: true(导航栏同理)
disableKeyboardProviderBool跳过内置的 KeyboardProvider 包装;默认 false。当你的应用已在根部挂载自己的 KeyboardProvider,或默认 edge-to-edge 行为在 Android/Expo 上引起布局位移、挂载闪烁、头部跳动时,开启此选项
keyboardAvoidingViewPropsObject透传给 KeyboardAvoidingView 的 Props,配合 keyboardVerticalOffset 正确处理键盘
isAlignedTopBoolean消息气泡是否从聊天顶部开始排列(默认 false,气泡底部对齐)
isInvertedBool反转 messages 的显示顺序;默认 true
深入理解 keyboardVerticalOffset

keyboardVerticalOffset 告诉 KeyboardAvoidingView 它的容器相对屏幕顶部从何处开始。当 GiftedChat 不在屏幕最顶端(例如存在导航栏)时,这一配置是必需的。

  • 默认值:insets.top(来自 useSafeAreaInsets() 的状态栏高度)。该默认值只有在 GiftedChat 全屏填充、没有导航栏时才正确。
  • 值的含义:偏移量等于从屏幕顶部到 GiftedChat 容器顶部的距离(pt),通常包含:
    • 状态栏高度;
    • 导航栏高度(iOS 上 useHeaderHeight() 已包含状态栏)。
  • 使用方法:
import { useHeaderHeight } from '@react-navigation/elements'

function ChatScreen() {
  // iOS 上 useHeaderHeight() 返回状态栏 + 导航栏高度
  const headerHeight = useHeaderHeight()

  return (
    <GiftedChat
      keyboardAvoidingViewProps={{ keyboardVerticalOffset: headerHeight }}
      // ... 其他 props
    />
  )
}

注意:useHeaderHeight() 要求聊天组件渲染在真正的导航 Screen 内(而非条件渲染)。如果它返回 0,请确认聊天页是带可见 header 的真实导航页面。

为什么重要:偏移量不正确时,键盘会遮挡输入框或留下多余空白——KeyboardAvoidingView 正是依靠这个值来计算键盘弹出时内容需要上移多少。

使用自己的 KeyboardProvider

默认情况下 GiftedChat 会用一个启用了 statusBarTranslucent 与 navigationBarTranslucent 的 KeyboardProvider 包裹自身。在某些 Android/Expo(edge-to-edge)环境中,这可能造成屏幕整体下移、挂载时闪烁、或导航栏变形——尤其是树上已经存在另一个 KeyboardProvider 时。

设置 disableKeyboardProvider 即可跳过内置包装:

import { KeyboardProvider } from 'react-native-keyboard-controller'

// 在应用根部只挂载一个 KeyboardProvider
function App() {
  return (
    <KeyboardProvider>
      {/* ...导航/页面... */}
    </KeyboardProvider>
  )
}

function ChatScreen() {
  return (
    <GiftedChat
      disableKeyboardProvider
      // ... 其他 props
    />
  )
}

重要:GiftedChat 的键盘避让依赖树中存在 KeyboardProvider。设置 disableKeyboardProvider 后,你必须在 GiftedChat 上方自行挂载 KeyboardProvider,否则键盘会遮挡输入框。全局只挂载一个 provider(你自己的),正是为了避免双重 edge-to-edge 位移。

文本输入与输入工具栏(Text Input & Composer)

Prop类型说明
textString输入文本;默认 undefined。一旦指定,将覆盖 GiftedChat 内部状态,适合用 Redux 等外部管理文本状态。别忘了在 textInputProps.onChangeText 中同步更新文本状态
initialTextString输入框的初始文本
isSendButtonAlwaysVisibleBool是否始终显示发送按钮;默认 false(仅在输入非空时显示)
isTextOptionalBool允许发送无文本消息(适合纯媒体消息);默认 false。配合 isSendButtonAlwaysVisible 可用于媒体附件场景
minComposerHeightObjectComposer 的最小高度
maxComposerHeightObjectComposer 的最大高度
minInputToolbarHeightInteger输入工具栏最小高度;默认 44
renderInputToolbarComponent | Function自定义消息输入容器
renderComposerComponent | Function自定义文本输入 Composer
renderSendComponent | Function自定义发送按钮;可直接给原 Send 组件传 children 实现自定义图标
renderActionsComponent | Function消息 Composer 左侧的自定义操作按钮
renderAccessoryComponent | FunctionComposer 下方的自定义第二行操作
textInputPropsObject透传给 <TextInput> 的 Props

在 src/GiftedChat/index.tsx 中可以看到 _onChangeText 的实现逻辑:它总是调用用户传入的 textInputProps.onChangeText 转发事件,并且只有当 props.text 为 undefined(非受控)时才更新内部状态,这与"text 是受控 prop"的语义完全一致。发送流程(_onSend,见 src/GiftedChat/index.tsx)会自动为新消息补充 createdAt: new Date()、生成的 _id、当前 user,并在存在回复消息时附加 replyMessage,发送完成后自动清空输入框并滚动到底部。

Actions 与 Action Sheet

Prop类型说明
onPressActionButtonFunction点击 Action 按钮时的回调(设置后默认的 actionSheet 将不再使用)
actionSheetFunction自定义展示操作选项的 action sheet 接口
actionsArray输入工具栏操作按钮的自定义操作项:{ title: string, action: () => void }[]
actionSheetOptionTintColorStringAction sheet 选项的 tint 颜色

消息与消息容器(Messages & Message Container)

Prop类型说明
messagesContainerStyleObject消息容器自定义样式
renderMessageComponent | Function自定义单条消息容器
renderLoadingComponent | Function初始化时的加载视图
renderChatEmptyComponent | Function消息列表为空时渲染的自定义组件
renderChatFooterComponent | Function渲染在 MessagesContainer 下方(独立于 ListView)的自定义组件
listPropsObject透传给消息 <FlatList> 的额外 Props,支持全部 FlatList 属性,包括用于 AI 聊天机器人场景的 maintainVisibleContentPosition

消息气泡与内容(Message Bubbles & Content)

Prop类型说明
renderBubbleComponent | Function(props: BubbleProps)自定义消息气泡。接收 src/Bubble/types.ts 中定义的 BubbleProps
renderMessageTextComponent | Function自定义消息文本
renderMessageImageComponent | Function自定义消息图片
renderMessageVideoComponent | Function自定义消息视频
renderMessageAudioComponent | Function自定义消息音频
renderCustomViewComponent | Function气泡内部的自定义视图
isCustomViewBottomBoolrenderCustomView 是否在文本、图片、视频视图之后展示;默认 false
onPressMessageFunction(context, message)点击消息气泡的回调
onLongPressMessageFunction(context, message)长按消息气泡的回调;可在此弹出 action sheet(如复制、删除、回复)
imagePropsObject透传给默认 renderMessageImage 创建的 <Image> 的额外 Props
imageStyleObject消息图片的自定义样式
videoPropsObject透传给必需的 renderMessageVideo 所创建视频组件的额外 Props
messageTextPropsObject透传给 MessageText 组件的额外 Props,用于定制链接解析行为、文本样式与 matchers

messageTextProps 支持的子属性包括:

子属性说明
matchers自定义链接匹配器(URL、电话、hashtag、mention 等)
linkStyle链接的自定义样式
email是否解析邮箱(默认 true)
phone是否解析电话号码(默认 true)
url是否解析 URL(默认 true)
hashtag是否解析 hashtag(默认 false)
mention是否解析 @ 提及(默认 false)
hashtagUrlhashtag 的基础 URL(如 'https://x.com/hashtag')
mentionUrlmention 的基础 URL(如 'https://x.com')
stripPrefix显示链接时是否去掉 http:// / https:// 前缀(默认 false)
TextComponent自定义用于渲染的 Text 组件(如来自 react-native-gesture-handler 的 TextInput 场景)

自定义 matchers 的完整示例:

<GiftedChat
  messageTextProps={{
    phone: false, // 关闭默认的电话号码链接
    matchers: [
      {
        type: 'phone',
        pattern: /\+?[1-9][0-9\-\(\) ]{7,}[0-9]/g,
        getLinkUrl: (replacerArgs: ReplacerArgs): string => {
          return replacerArgs[0].replace(/[\-\(\) ]/g, '')
        },
        getLinkText: (replacerArgs: ReplacerArgs): string => {
          return replacerArgs[0]
        },
        style: styles.linkStyle,
        onPress: (match: CustomMatch) => {
          const url = match.getAnchorHref()

          const options: {
            title: string
            action?: () => void
          }[] = [
            { title: 'Copy', action: () => setStringAsync(url) },
            { title: 'Call', action: () => Linking.openURL(`tel:${url}`) },
            { title: 'Send SMS', action: () => Linking.openURL(`sms:${url}`) },
            { title: 'Cancel' },
          ]

          showActionSheetWithOptions({
            options: options.map(o => o.title),
            cancelButtonIndex: options.length - 1,
          }, (buttonIndex?: number) => {
            if (buttonIndex === undefined)
              return

            const option = options[buttonIndex]
            option.action?.()
          })
        },
      },
    ],
    linkStyle: { left: { color: 'blue' }, right: { color: 'lightblue' } },
  }}
/>

完整示例参见 example/components/chat-examples/LinksExample.tsx。

头像(Avatars)

Prop类型说明
renderAvatarComponent | Function自定义消息头像;设为 null 则不渲染任何头像
isUserAvatarVisibleBool是否为当前用户渲染头像;默认 false,只显示其他用户的头像
isAvatarVisibleForEveryMessageBool为 false 时,仅在连续消息来自同一用户且同一天时显示头像;默认 false
onPressAvatarFunction(user)点击消息头像的回调
onLongPressAvatarFunction(user)长按消息头像的回调
isAvatarOnTopBool在连续消息顶部(而非底部)渲染头像;默认 false

用户名(Username)

Prop类型说明
isUsernameVisibleBool是否在消息气泡内展示用户名;默认 false
renderUsernameComponent | Function自定义用户名容器

日期与时间(Date & Time)

Prop类型说明
timeFormatString时间的渲染格式;默认 'LT'(Day.js Format)
dateFormatString日期的渲染格式;默认 'D MMMM'(Day.js Format)
dateFormatCalendarObject相对时间的渲染格式;默认 { sameDay: '[Today]' }(Day.js Calendar 插件)
renderDayComponent | Function自定义消息上方的日期分隔。同一函数同时负责内联日期分隔与"悬浮/带动画的吸顶日期头";读取 props.isAnimated(true 为悬浮头,false 为内联分隔)可分别定制外观
dayPropsObject透传给 Day 组件的 Props:containerStyle、wrapperStyle、textProps(如 style、allowFontScaling、numberOfLines)
renderTimeComponent | Function消息内的时间自定义渲染
timeTextStyleObject消息内时间的文本样式(支持 left/right 两侧)
isDayAnimationEnabledBool是否启用滚动时出现的动画日期标签;默认 true

常量 DATE_FORMAT = 'D MMMM' 与 TIME_FORMAT = 'LT' 定义在 src/Constant.ts 中,与上述默认值一一对应。动画日期头的详细规格可参考仓库内的 docs/DAY_ANIMATED_SPEC.md 与实现 src/MessagesContainer/components/DayAnimated/index.tsx。

系统消息(System Messages)

Prop类型说明
renderSystemMessageComponent | Function自定义系统消息

加载更早消息(Load Earlier Messages)

Prop类型说明
loadEarlierMessagesPropsObject透传给 LoadEarlierMessages 组件的 Props,按钮仅在 isAvailable 为 true 时可见

loadEarlierMessagesProps 支持的子属性:

子属性说明
isAvailable控制按钮可见性(默认 false)
onPress点击按钮的回调
isLoading显示加载指示器(默认 false)
isInfiniteScrollEnabled启用滚到消息顶部时自动触发 onPress 的无限滚动(Web 暂不支持)
label覆盖默认的 "Load earlier messages" 文本
containerStyle按钮容器样式
wrapperStyle按钮 wrapper 样式
textStyle按钮文本样式
activityIndicatorStyle加载指示器样式
activityIndicatorColor加载指示器颜色(默认 'white')
activityIndicatorSize加载指示器大小(默认 'small')

对照 src/LoadEarlierMessages.tsx 源码可以看到这些默认值(label = 'Load earlier messages'、activityIndicatorColor = 'white'、activityIndicatorSize = 'small')的真实落点,加载期间按钮会通过 enabled={!isLoading} 禁用并显示 ActivityIndicator,同时声明了 accessibilityRole='button' 以保证无障碍语义。

Typing Indicator(正在输入指示器)

Prop类型说明
isTypingBool正在输入状态;默认 false。如果使用 renderFooter 会覆盖此行为
renderTypingIndicatorComponent | Function自定义正在输入指示器
typingIndicatorStyleStyleProp<ViewStyle>TypingIndicator 组件的自定义样式
renderFooterComponent | FunctionListView 底部的自定义 footer 组件(例如 "User is typing...")。使用后覆盖 isTyping 触发的默认指示器

快捷回复(Quick Replies)

快捷回复的消息数据示例见 example/example-expo/data/messages.ts。

Prop类型说明
onQuickReplyFunction发送快捷回复时的回调(用于通知后端)
renderQuickRepliesFunction自定义整个快捷回复视图
quickReplyStyleStyleProp<ViewStyle>快捷回复视图样式
quickReplyTextStyleStyleProp<TextStyle>快捷回复按钮文本样式
quickReplyContainerStyleStyleProp<ViewStyle>快捷回复容器样式
renderQuickReplySendFunction自定义快捷回复的 发送 视图

深度功能实战

↩️ 回复消息(Reply to Messages)

Gifted Chat 开箱即用地支持滑动回复:用户滑动消息即可回复,输入工具栏会显示回复预览,新消息气泡上方会展示被回复的消息。

注意:该功能使用 react-native-gesture-handler 的 ReanimatedSwipeable 与 react-native-reanimated 实现流畅的动画效果。

基本用法
<GiftedChat
  messages={messages}
  onSend={onSend}
  user={{ _id: 1 }}
  reply={{
    swipe: {
      isEnabled: true,
      direction: 'left', // 左滑回复
    },
  }}
/>
Reply Props(分组结构)

reply prop 接受一个对象,结构定义在 src/Reply/types.ts:

interface ReplyProps<TMessage> {
  // 滑动手势配置
  swipe?: {
    isEnabled?: boolean              // 启用滑动回复;默认 false
    direction?: 'left' | 'right'     // 滑动方向;默认 'left'
    onSwipe?: (message: TMessage) => void  // 滑动触发后的回调
    renderAction?: (                 // 自定义滑动操作组件
      progress: SharedValue<number>,
      translation: SharedValue<number>,
      position: 'left' | 'right'
    ) => React.ReactNode
    actionContainerStyle?: StyleProp<ViewStyle>
  }

  // 回复预览样式(输入工具栏上方)
  previewStyle?: {
    containerStyle?: StyleProp<ViewStyle>
    textStyle?: StyleProp<TextStyle>
    imageStyle?: StyleProp<ImageStyle>
  }

  // 气泡内回复引用样式
  messageStyle?: {
    containerStyle?: StyleProp<ViewStyle>
    containerStyleLeft?: StyleProp<ViewStyle>
    containerStyleRight?: StyleProp<ViewStyle>
    textStyle?: StyleProp<TextStyle>
    textStyleLeft?: StyleProp<TextStyle>
    textStyleRight?: StyleProp<TextStyle>
    imageStyle?: StyleProp<ImageStyle>
  }

  // 回调与状态
  message?: ReplyMessage             // 受控的回复状态
  onClear?: () => void               // 回复被清除时调用
  onPress?: (message: TMessage) => void  // 点击回复预览时调用

  // 自定义渲染
  renderPreview?: (props: ReplyPreviewProps) => React.ReactNode
  renderMessageReply?: (props: MessageReplyProps) => React.ReactNode
}
ReplyMessage 结构

当消息包含回复时,它会携带 replyMessage 属性:

interface ReplyMessage {
  _id: string | number
  text: string
  user: User
  image?: string
  audio?: string
}

(源码定义见 src/Models.ts:ReplyMessage extends Pick<IMessage, '_id' | 'text' | 'user' | 'audio' | 'image'>。)

结合外部状态的高级示例
const [replyMessage, setReplyMessage] = useState<ReplyMessage | null>(null)

<GiftedChat
  messages={messages}
  onSend={messages => {
    const newMessages = messages.map(msg => ({
      ...msg,
      replyMessage: replyMessage || undefined,
    }))
    setMessages(prev => GiftedChat.append(prev, newMessages))
    setReplyMessage(null)
  }}
  user={{ _id: 1 }}
  reply={{
    swipe: {
      isEnabled: true,
      direction: 'right',
      onSwipe: setReplyMessage,
    },
    message: replyMessage,
    onClear: () => setReplyMessage(null),
    onPress: (msg) => scrollToMessage(msg._id),
  }}
/>

从 src/GiftedChat/index.tsx 的源码可以看到,回复状态支持受控/非受控两种模式:当 reply.message prop 为 undefined 时,组件内部用 internalReplyMessage 自行管理状态(非受控);一旦传入 reply.message 则完全由外部控制,onSwipe 回调里也只做转发。

平滑动画

回复预览会自动动画:

  • 出现时:从零高度平滑展开并伴随淡入效果;
  • 消失时:平滑收起并伴随淡出效果;
  • 内容变化时:切换到回复另一条消息时平滑过渡。

这些动画基于 react-native-reanimated 实现,可达到 60fps 性能。

⬇️ 回到底部(Scroll to Bottom)

Prop类型说明
isScrollToBottomEnabledBool启用回到底部组件(默认 false)
scrollToBottomComponentFunction自定义回到底部组件容器
scrollToBottomOffsetInteger开始显示回到底部组件的偏移阈值(默认 200)
scrollToBottomStyleObject回到底部 wrapper 样式(position、bottom、right 等)
scrollToBottomContentStyleObject回到底部内容样式(尺寸、背景、阴影等)

🤖 保持滚动位置(AI 聊天机器人场景)

在 AI 聊天界面中,长回复到达时不应打断用户的阅读位置。通过 listProps 使用 maintainVisibleContentPosition:

// 基础用法 - 始终维持滚动位置
<GiftedChat
  listProps={{
    maintainVisibleContentPosition: {
      minIndexForVisible: 0,
    },
  }}
/>

// 带自动滚动阈值 - 距离最新内容 10 像素内时自动滚动
<GiftedChat
  listProps={{
    maintainVisibleContentPosition: {
      minIndexForVisible: 0,
      autoscrollToTopThreshold: 10,
    },
  }}
/>

// 根据滚动状态条件启用(推荐用于聊天机器人)
const [isScrolledUp, setIsScrolledUp] = useState(false)

<GiftedChat
  listProps={{
    onScroll: (event) => {
      setIsScrolledUp(event.contentOffset.y > 50)
    },
    maintainVisibleContentPosition: isScrolledUp
      ? { minIndexForVisible: 0, autoscrollToTopThreshold: 10 }
      : undefined,
  }}
/>

😀 Emoji 表情反应(Emoji Reactions)

长按消息可打开快速表情选择器;选中的反应以药丸(pill)形式展示在气泡下方,点击可切换开关。核心库自带轻量级快速选择器(基于 react-native-gesture-handler 与 react-native-reanimated,无额外依赖);完整表情浏览器是可选项,示例应用中通过 renderReactionPicker 覆盖实现。

长按消息弹出的快速表情选择器

消息下方的表情反应药丸

(仓库 media 目录中的 reactions-picker.png 与 reactions-pills.png 展示了上述两个界面的真实效果。)

反应状态存放在每条消息的 reactions 数组上,启用该功能并处理 toggle 即可。反应状态由你(业务方)持有,因此可以适配任意后端:

interface IChatMessage extends IMessage {
  reactions?: MessageReaction[] // { emoji: string, userIds: (string | number)[] }[]
}

const CURRENT_USER_ID = 1

const handleReactionPress = useCallback((message: IChatMessage, emoji: string) => {
  setMessages(prev =>
    prev.map(m => {
      if (m._id !== message._id)
        return m

      const existing = (m.reactions ?? []).find(r => r.emoji === emoji)
      if (!existing)
        return { ...m, reactions: [...(m.reactions ?? []), { emoji, userIds: [CURRENT_USER_ID] }] }

      const userIds = existing.userIds.includes(CURRENT_USER_ID)
        ? existing.userIds.filter(id => id !== CURRENT_USER_ID)
        : [...existing.userIds, CURRENT_USER_ID]

      return {
        ...m,
        reactions: userIds.length === 0
          ? (m.reactions ?? []).filter(r => r.emoji !== emoji)
          : (m.reactions ?? []).map(r => (r.emoji === emoji ? { ...r, userIds } : r)),
      }
    })
  )
}, [])

<GiftedChat
  messages={messages}
  onSend={onSend}
  user={{ _id: CURRENT_USER_ID }}
  reactions={{
    isEnabled: true,
    onReactionPress: handleReactionPress,
    // 可选:提供更丰富的选择器(如全量表情浏览器)。
    // 参见 example/components/chat-examples/ReactionsExample.tsx
    // renderReactionPicker: props => <MyEmojiPicker {...props} />,
  }}
/>

完整示例见 example/components/chat-examples/ReactionsExample.tsx。

Reactions Props(分组结构)

reactions prop 的类型定义在 src/Reactions/types.ts:

Prop说明
isEnabled启用表情反应(默认 false)
emojis快速选择器中展示的表情(默认 ['👍', '❤️', '😂', '😮', '😢', '👎'])
onReactionPress(message, emoji) => void,选中表情或点击药丸时调用。toggle 逻辑由你实现
renderReactions覆盖气泡下方反应展示组件
renderReactionPicker覆盖长按弹出的选择器(用于接入全量表情浏览器)
containerStyle / reactionStyle / reactionActiveStyle / reactionTextStyle / reactionCountStyle反应药丸相关样式
pickerContainerStyle / pickerEmojiStyle快速选择器样式

默认表情列表以常量 DEFAULT_REACTION_EMOJIS 的形式定义在 src/Reactions/index.ts 中。类型层面,选择器组件接收的 ReactionPickerProps 还包含 visible、pageX、pageY、bubbleWidth、bubbleHeight 等几何信息(见 src/Reactions/types.ts),方便自定义选择器在气泡附近精确定位。

🔗 智能链接解析(Smart Link Parsing)

消息文本会自动扫描 URL、邮箱与电话号码;hashtag 与 @ 提及默认关闭、按需开启。通过 messageTextProps 配置:

<GiftedChat
  messageTextProps={{
    url: true,        // 默认 true
    email: true,      // 默认 true
    phone: true,      // 默认 true
    hashtag: true,    // 默认 false
    mention: true,    // 默认 false
    hashtagUrl: 'https://example.com/hashtag',
    mentionUrl: 'https://example.com',
    linkStyle: { left: { color: '#1d9bf0' }, right: { color: '#fff' } },
    onPress: (message, url, type) => {
      // type: 'url' | 'email' | 'phone' | 'mention' | 'hashtag'
      Linking.openURL(url)
    },
  }}
/>

底层实现:链接解析逻辑集中在 src/linkParser.tsx。源码定义了 DEFAULT_MATCHERS 数组(src/linkParser.tsx),为五种类型提供了默认正则与 URL 转换规则:

  • url:匹配 https?://、www. 前缀与裸域名;非 http(s) 开头的自动补全为 http:// 前缀;
  • email:标准邮箱正则,生成 mailto: 链接;
  • phone:宽松的电话号码正则,去除空格/括号/连字符后生成 tel: 链接;
  • hashtag:匹配 #[\w]+,可配合 hashtagUrl 拼出完整跳转地址;
  • mention:匹配 @[\w-]+,可配合 mentionUrl 拼出完整跳转地址。

解析流程(parseLinks,src/linkParser.tsx)遍历每个 matcher 收集全部命中,按索引排序后用 removeOverlaps 去重重叠区间,保证同一段文本不会被多个规则重复包裹。需要完全控制时,可传入自定义 matchers({ type, pattern, getLinkUrl?, getLinkText?, renderLink?, onPress? }[])来新增或覆盖规则,详见 example/components/chat-examples/LinksExample.tsx。

📋 复制到剪贴板(Copy to Clipboard)

长按处理通过 onLongPressMessage 暴露。GiftedChat 内部封装了 @expo/react-native-action-sheet,因此你可以弹出 "Copy Text" 操作并配合任意剪贴板库完成复制:

import { useActionSheet } from '@expo/react-native-action-sheet'
import { setStringAsync } from 'expo-clipboard'

const { showActionSheetWithOptions } = useActionSheet()

<GiftedChat
  onLongPressMessage={(_context, message) => {
    showActionSheetWithOptions(
      { options: ['Copy Text', 'Cancel'], cancelButtonIndex: 1 },
      buttonIndex => {
        if (buttonIndex === 0)
          setStringAsync(message.text)
      }
    )
  }}
/>

✅ 消息状态(Message Status)

为消息设置 sent、received 或 pending 即可展示投递状态。默认情况下它们以勾选标记渲染在时间戳旁边(✓ 已发送、✓✓ 已送达、🕓 发送中):

const message: IMessage = {
  _id: 1,
  text: 'Delivered!',
  createdAt: new Date(),
  user: { _id: 1 },
  sent: true,
  received: true,
}

使用 renderTicks(整体覆盖)或 tickStyle(仅样式)定制指示器:

<GiftedChat
  renderTicks={message => (message.received ? <MyReadIcon /> : null)}
  tickStyle={{ color: '#1d9bf0' }}
/>

📝 TypeScript:端到端类型安全

GiftedChat 随库发布完整类型定义,并且泛型化于你的消息类型。扩展 IMessage 添加自定义字段后,全程保持类型推导:

import { GiftedChat, IMessage } from 'react-native-gifted-chat'

interface MyMessage extends IMessage {
  reactions?: { emoji: string, userIds: (string | number)[] }[]
}

<GiftedChat<MyMessage>
  messages={messages}
  onSend={msgs => {/* msgs 被推导为 MyMessage[] */}
  user={{ _id: 1 }}
/>

onSend 中 msgs 的静态类型将自动是 MyMessage[],自定义字段在消息构造、渲染回调(如 renderBubble、onPressMessage)中都能获得完整补全。所有公共组件(Bubble、MessageText、InputToolbar、Send、Time、Day 等)也从 src/index.ts 统一导出,方便组合复用。

📱 平台注意事项

Android:键盘配置

如果使用 Create React Native App / Expo,无需额外的 Android 配置。否则建议修改项目配置:

确保 AndroidManifest.xml 中有 android:windowSoftInputMode="adjustResize":

<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:windowSoftInputMode="adjustResize"
  android:configChanges="keyboard|keyboardHidden|orientation|screenSize">

对于 Expo,可以在 GiftedChat 之后追加 KeyboardAvoidingView(仅 Android):

<View style={{ flex: 1 }}>
   <GiftedChat />
   {Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />}
</View>

🌐 Web(react-native-web)

配合 create-react-app 使用时:

  1. 安装 react-app-rewired:yarn add -D react-app-rewired
  2. 创建 config-overrides.js:
module.exports = function override(config, env) {
  config.module.rules.push({
    test: /\.js$/,
    exclude: /node_modules/\\/,
    use: {
      loader: 'babel-loader',
      options: {
        babelrc: false,
        configFile: false,
        presets: [
          ['@babel/preset-env', { useBuiltIns: 'usage' }],
          '@babel/preset-react',
        ],
        plugins: ['@babel/plugin-proposal-class-properties'],
      },
    },
  })
  return config
}

该配置的核心是让 babel-loader 处理 react-native-gifted-chat 包内的 ESM/JSX 源码(通过 exclude 正则放行),使其能在 web 构建链中被正确转译。

🧪 测试:触发布局事件

TEST_ID 以常量形式导出(定义在 src/Constant.ts:WRAPPER、LOADING_WRAPPER、SEND_TOUCHABLE),可配合任意测试库使用。

GiftedChat 通过 onLayout 确定聊天容器高度。测试中手动触发 onLayout:

const WIDTH = 200
const HEIGHT = 2000

const loadingWrapper = getByTestId(TEST_ID.LOADING_WRAPPER)
fireEvent(loadingWrapper, 'layout', {
  nativeEvent: {
    layout: {
      width: WIDTH,
      height: HEIGHT,
    },
  },
})

仓库内的测试用例(见 src/tests)覆盖了 Bubble、MessageText、Day、ReplyPreview、MessagesContainer 等核心组件,可作参考。

📦 运行示例应用(Example App)

仓库内置了展示全部特性的综合示例应用:

# 安装依赖(在 example 目录下)
cd example
yarn install

# 运行 iOS
npx expo run:ios

# 运行 Android
npx expo run:android

# 运行 Web
npx expo start --web

示例应用覆盖了以下功能:

❓ 常见问题(Troubleshooting)

TextInput 在 Android 上被遮挡

确保 AndroidManifest.xml 中配置了 android:windowSoftInputMode="adjustResize",详见上文 Android 配置。

如何为不同用户设置不同的气泡颜色?

可以通过 renderBubble 根据 currentMessage.user._id 判断发送方,为左右气泡返回不同的 wrapperStyle。参考社区 issue 中的做法,核心思路是让气泡样式成为 user 的函数。

如何定制 InputToolbar 样式?

使用 renderInputToolbar 或 renderComposer 覆盖组件,或利用 minInputToolbarHeight、minComposerHeight、maxComposerHeight 调整尺寸;样式上的微调可以通过 renderAccessory、textInputProps 完成。

如何手动收起键盘?

通过 textInputRef 拿到输入框实例后调用 blur(),或在页面层使用 Keyboard.dismiss()。

如何使用 renderLoading?

传入 renderLoading={() => <ActivityIndicator />} 即可在初始化阶段渲染自定义加载视图;测试时可结合上文 TEST_ID.LOADING_WRAPPER 触发 onLayout 完成初始化。

提问前的准备顺序:先查阅本 README,再搜索既有 issue,然后可在 StackOverflow 等平台按 react-native-gifted-chat 标签提问,最后如需可新建 issue。

开发与贡献

仓库欢迎任何形式的贡献,核心流程为:

  1. Fork 仓库
  2. 创建特性分支(git checkout -b feature/amazing-feature)
  3. 安装依赖(yarn install)
  4. 修改代码
  5. 运行测试(yarn test)
  6. 运行 Lint(yarn lint)
  7. 构建库(yarn build)
  8. 提交(git commit -m 'Add amazing feature')
  9. 推送分支并提交 Pull Request

开发环境常用命令:

yarn install        # 安装依赖
yarn build          # 构建库
yarn test           # 运行测试
yarn lint           # 运行 Lint
yarn prepublishOnly # 完整校验

项目采用 MIT 许可,由 React Native 社区共同维护。

结语

react-native-gifted-chat 的价值在于把聊天界面中最繁琐、最容易出错的工程问题(键盘避让、消息分页、手势动画、链接解析、日期本地化)全部封装为声明式 Props,同时保留从组件到渲染函数的全链路可定制性。本文以官方 README 为骨架、仓库源码为印证,完整覆盖了从安装到高级特性的全部环节。在实际项目中,建议从 example 目录的示例出发按需裁剪,并在升级依赖时留意 README 中关于维护模式与迁移 fork 的说明。

【免费下载链接】react-native-gifted-chat 💬 The most complete chat UI for React Native 【免费下载链接】react-native-gifted-chat 项目地址: https://gitcode.com/gh_mirrors/re/react-native-gifted-chat

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值