ChatScreen.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. import { userInfo } from 'os';
  15. export default function ChatScreen({ navigation, route }: StackScreenProps) {
  16. const { params } = route;
  17. const { toUserId, toUserName } = params;
  18. const { t } = useTranslation();
  19. if (toUserName) {
  20. navigation.setOptions({
  21. title: toUserName,
  22. });
  23. }
  24. const { userInfo }
  25. } = useModel("userModel");
  26. const {id}=userInfo;
  27. const [messages, setMessages] = useState([]);
  28. const { sendMessage,chatInfo } = useModel('IMModel');
  29. const { httpGet,httpPost } = useModel("httpModel");
  30. const { loading, run } = useRequest(
  31. ()=>{
  32. return httpGet(`/chat/showChat?userOne=${id}&userTwo=${toUserId}`)
  33. },
  34. {
  35. defaultLoading: false,
  36. initialData: [],
  37. onSuccess: (data) => {
  38. const list = data.map((item, index) => {
  39. return {
  40. _id: index,
  41. text: item.content,
  42. createdAt: parse(item.sendTime),
  43. user: {
  44. _id: item.sendUserId,
  45. name: item.sendNickName,
  46. avatar: item.sendAvatar,
  47. },
  48. };
  49. });
  50. setMessages(list);
  51. },
  52. }
  53. );
  54. React.useEffect(() => {
  55. if (chatInfo && chatInfo.from === toUserId.toString()) {
  56. run();
  57. }
  58. }, [chatInfo]);
  59. const onSend = useCallback((messages = []) => {
  60. console.log(messages);
  61. sendMessage(messages[0].text, toUserId);
  62. setMessages((previousMessages) =>
  63. GiftedChat.append(previousMessages, messages)
  64. );
  65. }, []);
  66. return (
  67. <Div flex={1}>
  68. <GiftedChat
  69. placeholder={t('qing-shu-ru-liao-tian-nei-rong')}
  70. messages={messages}
  71. onSend={(messages) => onSend(messages)}
  72. showUserAvatar={true}
  73. user={{
  74. _id: userInfo.id,
  75. avatar: userInfo.avatar,
  76. }}
  77. />
  78. {/* {Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />} */}
  79. </Div>
  80. );
  81. }