使用React Native中的React Navigation设置和访问可变应用程序全局参数

时间:2017-05-09 08:57:04

标签: react-native react-navigation

有没有办法可以在React Navigation StackNavigator中声明可变的全局参数?我正试图在应用程序中实现全局变量的中心参考点。

假设这是我的index.android.js:

import {
AppRegistry
} from 'react-native';
import { StackNavigator } from 'react-navigation';

import {MainScreen} from './components/mainScreen';
import {SegundoScreen} from './components/segundoScreen';
import {TerceraScreen} from './components/terceraScreen';

const SampleAppStack = StackNavigator(
  {
    Home :                { screen : MainScreen },
    SegundoScreen :    { screen : SegundoScreen },
    TerceraScreen :        { screen : TerceraScreen }
  },
  {
    headerMode: 'none'
  },
  {
    appGlobalVariables: {
      Session : '',
      variable1 : 'cool',
      variable2 : 'coolant',
      variable3 : 'color',
      variable4 : 'none',
      objetoUno : {},
      objetoDos : {},
      objetoTres : {}
    }
  }
);

AppRegistry.registerComponent('SampleApplication', () => SampleAppStack);

然后在目录components / mainScreen.js中,我认为......

import React, { Component } from 'react';
import {Text,View} from 'react-native';

import { StackNavigator } from 'react-navigation';

class MainScreen extends Component {
  constructor(props) {
  super(props);
  this.state = {dummyProp:'dummyProp'};
 }

 render() {
  var {appGlobalVariables} = this.props.StackNavigator;
  return (
   <View>
     <Text>Received from App's global variables: {appGlobalVariables.variable1}</Text>
   </View>
  );
 }
}

export {MainScreen}

在目录components / segundoScreen.js中,我认为......

import React, { Component } from 'react';
import {Text,View} from 'react-native';

import { StackNavigator } from 'react-navigation';

class SegundoScreen extends Component {
  constructor(props) {
  super(props);
  this.state = {dummyProp:'dummyProp'};
 }

 render() {
  var {appGlobalVariables} = this.props.StackNavigator;
  return (
   <View>
     <Text>Received from App's global variables: {appGlobalVariables.variable2}</Text>
   </View>
  );
 }
}

export {SegundoScreen}

在目录components / terceraScreen.js中,我认为......

import React, { Component } from 'react';
import {Text,View} from 'react-native';

import { StackNavigator } from 'react-navigation';

class TerceraScreen extends Component {
  constructor(props) {
  super(props);
  this.state = {dummyProp:'dummyProp'};
 }

 render() {
  var {appGlobalVariables} = this.props.StackNavigator;
  return (
   <View>
     <Text>Received from App's global variables: {appGlobalVariables.variable3}</Text>
   </View>
  );
 }
}

export {TerceraScreen}

我已经尝试过了,但它没有用。

1 个答案:

答案 0 :(得分:0)

一个选项是使用此处提到的global https://stackoverflow.com/a/36994650/4805414。另请参阅所属问题的已接受答案。也许这也是你的另类选择。