react-native-gifted-chat 渲染属性(render props)完整定制指南:以 example-gifted-chat 为例
react-native-gifted-chat 渲染属性(render props)完整定制指南:以 example-gifted-chat 为例
导读
react-native-gifted-chat 提供了极其丰富的渲染属性(render props),允许开发者在不破坏组件既有功能的前提下,逐个替换聊天界面中的每个部件。本指南以仓库中 example/example-gifted-chat/README.md 文档及其配套示例工程为核心,系统讲解 renderInputToolbar、renderActions、renderComposer、renderSend、renderAvatar、renderBubble、renderSystemMessage、renderMessage、renderMessageText、renderCustomView 这十类核心渲染属性的正确用法。读完本文,你将掌握"既深度自定义样式,又完整保留发送、清空输入框等原生交互功能"的实战方案,并能直接照搬示例源码到自己的项目中。
一、为什么需要专门研究 render props
许多使用 react-native-gifted-chat 的开发者都会遇到两个核心困惑:
- render props 数量众多,到底该传什么? 每个渲染属性接收的 props 类型各不相同(
AvatarProps、BubbleProps、SendProps等),传错了对象、漏了属性都会导致运行异常。 - 如何在自定义组件的同时保留其原有功能? 这是最容易被忽略的陷阱。以发送按钮(send button)为例:如果你直接传入一个完全自绘的组件给
renderSend,发送成功后清空输入框文本这一内置行为就会随之丢失,因为默认的Send组件内部持有onSend与shouldResetInputToolbar的调用逻辑。
作者正是为了解决这些问题而编写了 example-gifted-chat 示例,并在 example/example-gifted-chat/README.md 中明确说明:"I made this for anyone who wants to know how to use the render Props properly."(我为所有想正确使用 render props 的人制作了此示例)。
示例的运行效果见下(完整 UI 截图):
二、十类核心渲染属性一览
原文档列出了如下渲染属性,这是整个示例的骨架。下面结合 src/GiftedChat/types.ts 中的类型定义,逐条给出其作用与签名:
| 渲染属性 | 对应的子组件 | 传入的 props 类型 | 核心作用 |
|---|---|---|---|
renderInputToolbar |
InputToolbar | InputToolbarProps<TMessage> |
整个输入工具栏容器,可传组件、元素、渲染函数或 null |
renderActions |
Actions | ActionsProps |
输入框左侧的"+"操作按钮 |
renderComposer |
Composer | ComposerProps |
消息文本输入框 |
renderSend |
Send | SendProps<TMessage> |
发送按钮 |
renderAvatar |
Avatar | AvatarProps<TMessage> |
每条消息的头像;传 null 则不渲染头像 |
renderBubble |
Bubble | BubbleProps<TMessage> |
消息气泡 |
renderSystemMessage |
SystemMessage | SystemMessageProps<TMessage> |
系统消息(如 system: true 的消息) |
renderMessage |
Message | MessageProps<TMessage> |
单条消息的整体容器 |
renderMessageText |
MessageText | MessageTextProps<TMessage> |
消息文本(含链接解析) |
renderCustomView |
自定义组件 | BubbleProps<TMessage> |
气泡内的自定义视图(默认为空,返回 null 即不渲染) |
从源码看,src/GiftedChat/types.ts 中这些属性的类型均为
(props: XxxProps<TMessage>) => React.ReactNode形式,唯一例外是renderAvatar可传null(表示完全不渲染头像),renderInputToolbar还额外支持直接传React.ReactElement组件元素。
三、顶层装配:一个完整使用 render props 的 GiftedChat 示例
原文档指出示例工程的目标是演示所有渲染属性的搭配使用。核心入口在 example/example-gifted-chat/src/Chats.tsx,它将渲染属性拆分成两组:消息区域相关的渲染函数集中在 customComponents.tsx,输入工具栏相关的组件集中在 InputToolbar.tsx。完整装配代码如下:
import React, { useState, useEffect } from 'react'
import { useColorScheme } from 'react-native'
import { GiftedChat, IMessage } from 'react-native-gifted-chat'
import { useKeyboardVerticalOffset } from '../../hooks/useKeyboardVerticalOffset'
import {
renderAvatar,
renderBubble,
renderSystemMessage,
renderMessage,
renderMessageText,
renderCustomView,
} from './customComponents'
import { RenderInputToolbar, RenderActions, RenderComposer, RenderSend } from './InputToolbar'
import initialMessages from './messages'
const Chats = () => {
const [text, setText] = useState('')
const [messages, setMessages] = useState<IMessage[]>([])
const colorScheme = useColorScheme()
const isDark = colorScheme === 'dark'
const keyboardVerticalOffset = useKeyboardVerticalOffset()
useEffect(() => {
setMessages(initialMessages.reverse())
}, [])
const onSend = (newMessages: IMessage[] = []) => {
setMessages(prevMessages => GiftedChat.append(prevMessages, newMessages))
}
return (
<GiftedChat
messages={messages}
text={text}
onSend={onSend}
user={{
_id: 1,
name: 'Aaron',
avatar: 'https://placeimg.com/150/150/any',
}}
isAlignedTop
isSendButtonAlwaysVisible
isScrollToBottomEnabled
// isUserAvatarVisible
isAvatarOnTop
isUsernameVisible
onPressAvatar={console.log}
renderInputToolbar={RenderInputToolbar}
renderActions={RenderActions}
renderComposer={RenderComposer}
renderSend={RenderSend}
renderAvatar={renderAvatar}
renderBubble={renderBubble}
renderSystemMessage={renderSystemMessage}
renderMessage={renderMessage}
renderMessageText={renderMessageText}
// renderMessageImage
renderCustomView={renderCustomView}
isCustomViewBottom
messagesContainerStyle={{ backgroundColor: isDark ? '#1a1a1a' : 'indigo' }}
textInputProps={{
style: isDark && { backgroundColor: '#2a2a2a', color: '#fff' },
onChangeText: setText,
}}
keyboardAvoidingViewProps={{ keyboardVerticalOffset }}
/>
)
}
export default Chats
代码中值得注意的搭配:
text={text}与textInputProps.onChangeText: setText配合,将输入文本提升为受控状态(原文:text一旦指定即覆盖 GiftedChat 内部状态,见 src/GiftedChat/types.ts)。isSendButtonAlwaysVisible让发送按钮始终显示,即使输入框为空(对应 src/GiftedChat/types.ts 与 src/Send.tsx 中isVisible的计算逻辑)。keyboardAvoidingViewProps={{ keyboardVerticalOffset }}用于适配 iOS 键盘避让(keyboardVerticalOffset需根据头部高度设置,约 44pt,见 src/GiftedChat/types.ts)。isCustomViewBottom控制自定义视图出现在文本/图片/视频的下方(默认false,见 src/GiftedChat/types.ts)。
四、输入工具栏定制:保留功能的正确姿势
原文档反复强调的核心理念是:自定义组件应该包装原始组件,而不是彻底替换它。正确做法是:把自己定义外观样式传给原始组件的对应 style 属性,同时用 {...props} 把 GiftedChat 注入的全部 props 透传给原始组件。
4.1 顶层容器:renderInputToolbar
示例将 RenderInputToolbar 定义为一个 React 组件(而非普通函数),并用 React.memo 包裹,这样它内部才能使用 hooks(示例中用于读取 useColorScheme):
// example/example-gifted-chat/src/InputToolbar.tsx
export const RenderInputToolbar = React.memo((props: InputToolbarProps<IMessage>) => {
const colorScheme = useColorScheme()
const isDark = colorScheme === 'dark'
return (
<InputToolbar
{...props}
containerStyle={{
backgroundColor: isDark ? '#1a1a1a' : '#222B45',
paddingTop: 6,
}}
primaryStyle={{ alignItems: 'center' }}
/>
)
})
containerStyle作用于整个工具栏的外层容器(源码中该容器还包含回复预览与 accessory 区域,见 src/InputToolbar.tsx)。primaryStyle作用于装载 Actions、Composer、Send 三者的行容器(flexDirection: 'row',见 src/InputToolbar.tsx)。- 由于是
{...props}透传,回复预览(reply preview)、accessory 等内部功能全部保留。
4.2 左侧按钮:renderActions
export const RenderActions = React.memo((props: ActionsProps) => {
const colorScheme = useColorScheme()
const isDark = colorScheme === 'dark'
return (
<Actions
{...props}
containerStyle={{
width: 44,
height: 44,
alignItems: 'center',
justifyContent: 'center',
marginLeft: 4,
marginRight: 4,
marginBottom: 0,
}}
icon={() => (
<Image
style={{ width: 32, height: 32 }}
source={{ uri: 'https://placeimg.com/32/32/any' }}
/>
)}
options={{
'Choose From Library': () => {
console.log('Choose From Library')
},
Cancel: () => {
console.log('Cancel')
},
}}
optionTintColor={isDark ? '#ffffff' : '#222B45'}
/>
)
})
icon是渲染函数,替换默认的"+"图标(默认样式见 src/Actions.tsx)。options定义点击后弹出的 ActionSheet 菜单项,最后一项Cancel会作为cancelButtonIndex处理(src/Actions.tsx 中按titles.length - 1计算取消索引,因此务必把 Cancel 放在最后)。optionTintColor控制菜单文字颜色。
4.3 输入框:renderComposer
export const RenderComposer = React.memo((props: ComposerProps) => {
const colorScheme = useColorScheme()
const isDark = colorScheme === 'dark'
return (
<Composer
{...props}
textInputProps={{
style: {
color: isDark ? '#ffffff' : '#222B45',
backgroundColor: isDark ? '#2a2a2a' : '#EDF1F7',
borderWidth: 1,
borderRadius: 5,
borderColor: isDark ? '#3a3a3a' : '#E4E9F2',
paddingTop: 8.5,
paddingHorizontal: 12,
marginLeft: 0,
},
placeholderTextColor: isDark ? '#888' : undefined,
}}
/>
)
})
通过 textInputProps 覆盖 TextInput 的样式,实现圆角、内边距与明暗双主题配色,输入逻辑完全不受影响。
4.4 发送按钮:renderSend(原文档重点示例)
这正是原文档开头警告的场景——"自定义 send button 后丢失清空文本功能"。示例的解法是继续使用原始 Send 组件并传入自定义 children:
export const RenderSend = React.memo((props: SendProps<IMessage>) => (
<Send
{...props}
isDisabled={!props.text}
containerStyle={{
width: 44,
height: 44,
alignItems: 'center',
justifyContent: 'center',
marginHorizontal: 4,
}}
>
<Image
style={{ width: 32, height: 32 }}
source={{ uri: 'https://placeimg.com/32/32/any' }}
/>
</Send>
))
从源码看保留功能的关键机制:src/Send.tsx 中的 handleOnPress 会调用 onSend(message, true)——第二个参数 shouldResetInputToolbar = true 正是"发送成功后清空输入框"的开关;而 children 存在时仅替换按钮的可视内容(见 src/Send.tsx),点击行为依然是原始逻辑。这就是"自定义外观、保留功能"的标准模板。
五、消息区域定制:样式覆盖与局部渲染
消息区域的渲染函数集中在 example/example-gifted-chat/src/customComponents.tsx,每个函数同样遵循"透传 props + 覆盖 style"的模式。
5.1 renderAvatar 与 renderBubble
export const renderAvatar = (props: AvatarProps<IMessage>) => (
<Avatar
{...props}
containerStyle={{ left: { borderWidth: 3, borderColor: 'red' } }}
imageStyle={{ left: { borderWidth: 3, borderColor: 'blue' } }}
/>
)
export const renderBubble = (props: BubbleProps<IMessage>) => (
<Bubble
{...props}
// renderTime={() => <Text>Time</Text>}
// renderTicks={() => <Text>Ticks</Text>}
containerStyle={{
left: { borderColor: 'teal', borderWidth: 8 },
}}
wrapperStyle={{
left: { borderColor: 'tomato', borderWidth: 4 },
}}
bottomContainerStyle={{
left: { borderColor: 'purple', borderWidth: 4 },
}}
usernameStyle={{ color: 'tomato', fontWeight: '100' }}
containerToNextStyle={{
left: { borderColor: 'navy', borderWidth: 4 },
}}
containerToPreviousStyle={{
left: { borderColor: 'mediumorchid', borderWidth: 4 },
}}
/>
)
注意这里大量使用 left/right 左右双份的样式结构(即 LeftRightStyle<T>,见 src/Models.ts 中 LeftRightStyle 类型定义),分别对应对方消息与己方消息。示例用不同颜色边框直观地区分气泡的各个层级:外层 containerStyle、中层 wrapperStyle、底部 bottomContainerStyle、以及用于连续消息衔接的 containerToNextStyle / containerToPreviousStyle。被注释掉的 renderTime 与 renderTicks 展示了对气泡内部子部件的局部覆写能力。
5.2 renderSystemMessage、renderMessage 与 renderMessageText
export const renderSystemMessage = (props: SystemMessageProps<IMessage>) => (
<SystemMessage
{...props}
containerStyle={{ backgroundColor: 'pink' }}
wrapperStyle={{ borderWidth: 10, borderColor: 'white' }}
textStyle={{ color: 'crimson', fontWeight: '900' }}
/>
)
export const renderMessage = (props: MessageProps<IMessage>) => (
<Message
{...props}
// renderDay={() => <Text>Date</Text>}
containerStyle={{
left: { backgroundColor: 'lime' },
right: { backgroundColor: 'gold' },
}}
/>
)
export const renderMessageText = (props: MessageTextProps<IMessage>) => (
<MessageText
{...props}
containerStyle={{
left: { backgroundColor: 'yellow' },
right: { backgroundColor: 'purple' },
}}
textStyle={{
left: { color: 'red' },
right: { color: 'green' },
}}
linkStyle={{
left: { color: 'orange' },
right: { color: 'orange' },
}}
customTextStyle={{ fontSize: 24, lineHeight: 24 }}
/>
)
renderSystemMessage三个层级(容器/包裹/文本)样式均可定制,示例用粉色背景 + 白色粗边框 + 深红粗体字呈现系统消息。renderMessage用left/right背景色区分对方与己方消息的整体底色。renderMessageText不仅支持containerStyle、textStyle、linkStyle(超链接颜色),还支持customTextStyle直接叠加文本样式。示例中fontSize: 24与 messages.ts 中一条带链接、邮箱、话题标签的长文本配合,可直观验证 linkParser 对 URL 与电话号码的解析着色(相关实现见 src/linkParser.tsx)。
5.3 renderCustomView:气泡内的自定义视图
interface CustomViewProps {
user: User
}
export const renderCustomView = ({ user }: CustomViewProps) => (
<View style={{ minHeight: 20, alignItems: 'center' }}>
<Text>
Current user:
{user.name}
</Text>
<Text>From CustomView</Text>
</View>
)
renderCustomView 接收的 props 中包含 user 字段(类型层面为 BubbleProps<TMessage>,见 src/GiftedChat/types.ts)。示例在每个气泡下方显示"当前用户名 + From CustomView"文本,再配合 isCustomViewBottom 决定其摆放位置。
六、示例消息数据与 quickReplies
example/example-gifted-chat/src/messages.ts 提供了可直接使用的演示数据,覆盖了 GiftedChat 消息模型的多种形态:
- 含链接、邮箱、电话号码与
#话题标签的长文本(用于验证链接解析); - 普通文本消息;
- 带图片的消息(
image字段); - 两条 quick replies 消息,分别演示
checkbox与radio两种类型,其中 radio 型设置了keepIt: true(点击选项后保留快捷回复条,values中的选项可包含 emoji 标题); - 系统消息(
system: true)。
数据构建时通过 .map() 为每条消息补充自增 _id 并 reverse(),与 GiftedChat 的倒序消息列表约定保持一致;Chats.tsx 中挂载时再用 setMessages(initialMessages.reverse()) 恢复正序展示,onSend 则使用 GiftedChat.append 在列表头部插入新消息(见 example/example-gifted-chat/src/Chats.tsx)。
七、运行与验证
example-gifted-chat 是 example Expo 工程中的页面之一。按 example/README.md 的指引:
- 安装依赖:先在仓库根目录执行
yarn install,再进入example目录执行yarn install; - 按需构建原生开发版本(仅需一次或重装原生依赖后):
yarn installDevBuild:ios或yarn installDevBuild:android; - 启动 iOS 模拟器:
yarn start:ios。
运行后可对照验证:
- 发送一条消息后,输入框应被自动清空(验证
renderSend保留了原始功能); - 点击左侧按钮弹出带"Choose From Library / Cancel"的 ActionSheet(验证
renderActions); - 明暗主题切换(iOS 模拟器
Cmd + Shift + A)时,输入工具栏、输入框、消息列表背景均随之变化(示例中通过useColorScheme实现,GiftedChat亦提供colorScheme属性强制指定明暗,见 src/GiftedChat/types.ts)。
八、总结:render props 定制的三条铁律
综合原文档与示例源码,可以总结出 react-native-gifted-chat 渲染属性定制的三条原则:
- 能包不换:优先用
{...props}包裹原始组件并覆写其 style 属性(containerStyle、wrapperStyle、textStyle、linkStyle等),功能由原始组件内部逻辑保证,绝不丢失; - 能传 children 就不自绘:如
Send按钮这类带行为的部件,通过children替换外观即可,点击行为(含shouldResetInputToolbar清空逻辑)天然保留; - 善用类型签名:每个渲染属性对应明确的 Props 类型(
AvatarProps、BubbleProps、SendProps等,均定义于 src/GiftedChat/types.ts),按类型编写渲染函数即可避免传参错误;需要 hooks 时用React.memo包裹成组件再传入。
按照以上方式,你就能像 example-gifted-chat 一样,用十来行代码让聊天界面脱胎换骨,同时保证发送、清空、ActionSheet、链接解析、快捷回复等全部原生能力原封不动。
