簡體   English   中英

是否可以在本機反應中從另一個 class 組件訪問 useRef 變量?

[英]Is it possible to access a useRef variable from another class component in react native?

我正在嘗試訪問在 class 組件中的功能組件中聲明的 useRef 變量。 這可能嗎? 目前,當我在我的 class 組件 FireMessage 中導入功能組件 DetailsScreen 時,並在 get db() function 中添加 console.log(DetailsScreen.receiverUid) 它返回“未定義”。 您知道是什么原因造成的,以及如何在 class 組件中訪問此變量嗎?

**DetailsScreen**


import 'react-native-gesture-handler';

import { Image, StyleSheet, Text, TouchableOpacity, View, ScrollView, 
SafeAreaView, FlatList, Alert, TouchableHighlight, Platform, Dimensions, 
Linking} from 'react-native';

import React, {useState, useContext, useRef} from 'react';


const DetailsScreen = ({route, navigation}) => {

    const receiverUid = useRef(route.params.key);
}


export default DetailsScreen;


**FireMessage**

import firebase from "firebase";
import firebaseConfig from './firebaseConfig.js';
import 'react-native-gesture-handler';
import * as React from 'react';
import DetailsScreen from './DetailsScreen.js';

class FireMessage {

 constructor() {
   this.init()
   this.checkAuth() 
 }

 init = () => {
   if (!firebase.apps.length && firebaseConfig.apps.length === 0) {
   firebase.initializeApp({
    apiKey: "xxxxxxxxxxx",
    authDomain: "xxxxxxxxxxx",
    databaseURL: "xxxxxxxxxx",
    projectId: "xxxxxxxx",
    storageBucket: "xxxxxxxxxx",
    messagingSenderId: "xxxxxxxx",
    appId: "xxxxxxxxxxx",
    measurementId: "xxxxxxxxx"
   });
  }
};

checkAuth = () => {
  firebase.auth().onAuthStateChanged(user => {
    if (!user) {
      firebase.auth().signInAnonymously();
    }
  });
};

send = messages => {
  messages.forEach(item => {
    const message = {
      text: item.text,
      timestamp: firebase.database.ServerValue.TIMESTAMP,
      user: item.user
    };

   this.db.push(message)
 });
};

parse = message => {
   const { user, text, timestamp } = message.val();
   const { key: _id } = message;
   const createdAt = new Date(timestamp);


   return {
    _id,
    createdAt,
    text,
    user
   };
};

get = callback => {
   this.db.on("child_added", snapshot => 
   callback(this.parse(snapshot)));
};

off() {
   this.db.off();
}

get db() {
   console.log(DetailsScreen.receiverUid)
   return firebase.database().ref("messages");
}

get uid() {
   return (firebase.auth().currentUser || {}).uid;
}
}

export default new FireMessage();

每當你更新receiverUid更新DetailsScreen.receiverUid

const newId = 'some-receiver-id'
receiverUid.current = newId
DetailScreen.receiverUid = newId

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM