ChatScreen.tsx 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { StackScreenProps } from '@react-navigation/stack';
  2. import React, { useState, useCallback, useEffect } from 'react';
  3. import { Platform, View, KeyboardAvoidingView } from 'react-native';
  4. import { Div, Button, Image, Text, Avatar } from 'react-native-magnus';
  5. import { GiftedChat } from 'react-native-gifted-chat';
  6. import { ScrollView } from 'react-native-gesture-handler';
  7. import * as Localization from 'expo-localization';
  8. import useModel from 'flooks';
  9. import User from '../stores/User';
  10. import IM from './model';
  11. import { parse } from '../utils/TimeUtils';
  12. import { useTranslation } from 'react-i18next';
  13. import { useRequest } from 'ahooks';
  14. export default function ChatScreen({ navigation, route }: StackScreenProps) {
  15. const { params } = route;
  16. const { toUserId, toUserName } = params;
  17. const { t } = useTranslation();
  18. if (toUserName) {
  19. navigation.setOptions({
  20. title: toUserName,
  21. });
  22. }
  23. const { id, userInfo, chatInfo } = useModel(User, [
  24. 'id',
  25. 'chatInfo',
  26. 'userInfo',
  27. ]);
  28. const [messages, setMessages] = useState([]);
  29. const { sendMessage } = useModel(IM, []);
  30. const { loading, run } = useRequest(
  31. `/chat/showChat?userOne=${id}&userTwo=${toUserId}`,
  32. {
  33. defaultLoading: false,
  34. initialData: [],
  35. onSuccess: (data) => {
  36. const list = data.map((item, index) => {
  37. return {
  38. _id: index,
  39. text: item.content,
  40. createdAt: parse(item.sendTime),
  41. user: {
  42. _id: item.sendUserId,
  43. name: item.sendNickName,
  44. avatar: item.sendAvatar,
  45. },
  46. };
  47. });
  48. setMessages(list);
  49. },
  50. }
  51. );
  52. React.useEffect(() => {
  53. if (chatInfo && chatInfo.from === toUserId.toString()) {
  54. run();
  55. }
  56. }, [chatInfo]);
  57. const onSend = useCallback((messages = []) => {
  58. console.log(messages);
  59. sendMessage(messages[0].text, toUserId);
  60. setMessages((previousMessages) =>
  61. GiftedChat.append(previousMessages, messages)
  62. );
  63. }, []);
  64. return (
  65. <Div flex={1}>
  66. <GiftedChat
  67. placeholder={t('qing-shu-ru-liao-tian-nei-rong')}
  68. messages={messages}
  69. onSend={(messages) => onSend(messages)}
  70. showUserAvatar={true}
  71. user={{
  72. _id: userInfo.id,
  73. avatar: userInfo.avatar,
  74. }}
  75. />
  76. {/* {Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />} */}
  77. </Div>
  78. );
  79. }