首页 > 解决方案 > 如何从 react-native 中的导入文件访问导航选项

问题描述

我通过不同的页面将数据传递到我的应用程序的最后一页,它工作正常。

但问题是最后一页有 2 个组件,所以很典型</ChatActivity navigation="{this.props.navigation}" />,这就是我的意思:

我有一个 App.js

App.js 的内容

import ChatScreen from './chat'
    class ChatActivity extends Component {
      static navigationOptions = {
        ...
      }
      render() {
        return(
            <ChatScreen navigation={this.props.navigation} />
        )
      }
    }

我也有包含聊天组件的 chat.js。Chat.js 本身,需要import Fire from './fire.js'

所以现在,this.props.navigation只传递给Chat.js...但我也需要从中访问它fire.js

我已经阅读过import {useNavigation},但是从我尝试过的内容来看,它不起作用,因为我fire.js的看起来甚至不像文档中的示例

这是我的fire.js

class Fire extends React.Component{
  constructor (props) {
    super(props)

    this.init()
    this.checkAuth()
  }
  init = () => {
        firebase.initializeApp({

        })
  };

  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,
       // image: item.image,
        //video: item.video,
        user: item.user
      }
      this.db.child(`NEED NAVIGATION PARAMS HERE`).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.child(`NEED NAVIGATION PARAMS HERE`).on('child_added', snapshot => callback(this.parse(snapshot)))
  }

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

  get db() {
    return firebase.database().ref(`NEED NAVIGATION PARAMS HERE`);
  }

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

export default new Fire();

由于我无法访问导航参数,所以我尝试AsyncStorage了,但这可能不是最佳做法,而且效果不太好。不确定是不是,AsyncStorage但是react-native-gifted-chat当我加载聊天页面一次时,它会为其他聊天显示相同的消息,直到我重新启动应用程序,这不应该是因为我正在根据唯一参数获取数据。

标签: reactjsreact-nativereact-navigationreact-native-navigationreact-native-gifted-chat

解决方案


你只是在这里错过了一步......

由于您已使用以下方法将导航作为道具传递:

<ChatScreen navigation={this.props.navigation} />

聊天屏幕开始使用ChatActivity的导航属性。

为了让 Fire.js也能够使用由ChatActivity提供给Chat.js的导航,您需要以相同的方式将 Chat.js 接收到的导航道具传递Fire.js。

你的Chat.js应该是这样的:

import Fire from './Fire'

class Chat extends Component {
    static navigationOptions = {
        ...
    }
    render() {
        return(
            <Fire navigation={this.props.navigation} />
        )
    }
}

那应该可以解决问题。干杯!


推荐阅读