我在 renderBubble 道具中使用 renderQuickreplies。如果您想自定义聊天组件,它会变得非常复杂。但这是我的示例:
我使用从默认的天才聊天消息扩展而来的自定义消息类型:
type MessageType =
| 'TEXT'
| 'AMOUNT_SLIDER'
| 'ERROR'
| 'WARNING'
| 'SCROLL_PICKER'
| 'IMAGE_BUBBLE_USER'
| 'FILE_BUBBLE_USER'
| 'FILE_SELECT'
| 'QUICKREPLIES'
| 'DATE';
export interface ChatMessage extends IMessage {
type: MessageType; //<- important part
sliderConfig?: SliderConfig;
dateConfig?: DateConfig;
imageConfig?: {
uri: string;
};
fileConfig?: {
uri: string;
name: string;
};
scrollOptions?: ScrollOption[];
cameraConfig?: {
type: 'front' | 'back';
};
quickReplies?: BotQuickReplies;
onClick?: () => void;
//..other props
}
GiftedChat:
//... other code
<GiftedChat
//...other props
messages={IMessages} //pass my custom messages array
renderBubble={(props: any) => (
<RenderComponents
props={props}
onQuickReply={onQuickReply}
setInput={setInput}
onTextChange={onTextChange}
locale={locale}
stepConfig={stepConfig}
IMessages={IMessages}
setIMessages={setIMessages}
openCamera={openCamera}
onComponentFinishedRendering={onComponentFinishedRendering}
removeErrors={removeErrors}
pushUserMessage={pushUserAnswer}
/>
)}
//...other props
/>
//...other code
渲染组件:
//...other code
const RenderComponents: React.FC<Props> = ({
props: giftedChatProps,
onQuickReply,
setInput,
onTextChange,
locale,
stepConfig,
IMessages,
setIMessages,
openCamera,
onComponentFinishedRendering,
removeErrors,
pushUserMessage,
}) => {
//...other code
const { currentMessage } = giftedChatProps;
const { type, _id } = currentMessage as ChatMessage;
switch (type) {
case 'SCROLL_PICKER': {
return (
<CustomScrollPicker
//...props
/>
);
}
case 'ERROR': {
return (
<ErrorBubble
//...props
/>
);
}
//...other message types
case 'QUICKREPLIES': {
return (
<QuickRepliesController
onQuickReply={onQuickReply}
quickReplies={currentMessage.quickReplies}
//...other props
/>
);
}
//...other message types
default: {
return null;
}
}
};
导出默认渲染组件;
最后是消息类型为“QUICKREPLIES”时的自定义聊天消息气泡,它通过另一个我不会在这里复制的动画层,它只是一堆动画功能,但最终渲染了这个基本上只是带有一些自定义样式按钮的视图框:
//...other code
const QuickRepliesBubble: FC<Props> = ({
quickReplies, //quickreplies array from message object
onQuickReply, //
}) => {
return (
<View style={styles.container}>
{quickReplies.values.map((reply: BotReply) => {
return (
<CustomQuickReply
image={reply.image}
key={reply.value}
title={reply.localizedTitle}
onPress={() =>
onQuickReply({
value: reply.value,
})
}
/>
);
})}
</View>
);
};
我知道这可能看起来像一堆代码块。但基本思想是您可以在 GiftedChat 组件中完全自定义渲染 renderBubble 属性。但是您需要找到一种在默认气泡和您自定义创建的气泡之间切换的方法。在我的例子中,我向我的消息对象添加了“类型”属性,并为不同类型的消息进行了切换。