javascript 如何使用Firebase在React导航中创建聊天功能

ruyhziif  于 2023-05-12  发布在  Java
关注(0)|答案(1)|浏览(106)

我正在做一个项目的旅行应用程序生活但卡在一个问题,我想创建一个聊天功能,但我不能这样做.我需要一个解决方案我还写了一个项目React Navigation用Firebase在React Navigation中创建聊天功能

gjmwrych

gjmwrych1#

你可以从这里开始修改

import React, { useEffect, useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList } from 'react-native';
import firebase from 'firebase';
import 'firebase/firestore';
import { useNavigation } from '@react-navigation/native';

const ChatScreen = () => {
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);
  const navigation = useNavigation();

  useEffect(() => {
    const messagesRef = firebase.firestore().collection('messages').orderBy('timestamp', 'desc');
    const unsubscribe = messagesRef.onSnapshot((querySnapshot) => {
      const data = [];
      querySnapshot.forEach((doc) => {
        data.push({
          ...doc.data(),
          id: doc.id,
        });
      });
      setMessages(data);
    });

    return () => unsubscribe();
  }, []);

  const handleSendMessage = () => {
    const { currentUser } = firebase.auth();
    const timestamp = firebase.firestore.FieldValue.serverTimestamp();
    firebase.firestore().collection('messages').add({
      text: message,
      senderId: currentUser.uid,
      timestamp,
    });
    setMessage('');
  };

  const renderItem = ({ item }) => (
    <View style={{ padding: 10 }}>
      <Text>{item.text}</Text>
    </View>
  );

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        data={messages}
        renderItem={renderItem}
        inverted
      />
      <View style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }}>
        <TextInput
          style={{ flex: 1, marginRight: 10 }}
          placeholder="Type a message"
          value={message}
          onChangeText={setMessage}
        />
        <TouchableOpacity onPress={handleSendMessage}>
          <Text>Send</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default ChatScreen;

相关问题