在同级之间传递数据|反应原生

时间:2018-09-26 12:39:56

标签: reactjs react-native redux mobx siblings

我在React Native中有一个问题,我想在2个同级组件之间共享一个数组。我的应用程序有一个底部导航器,其中,我定义了要在其中进行导航的组件:

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Icon from "react-native-vector-icons/Ionicons";
import { createBottomTabNavigator } from "react-navigation";
import MapScreen from './modules/Map';
import ProfileScreen from './modules/Profile';
import EventsScreen from './modules/Events';

export default createBottomTabNavigator(
  {
    Events: {
      screen: EventsScreen,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <Icon name="md-bookmark" color={tintColor} size={24} />
        )
      }
    },
    Map: {
      screen: MapScreen,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <Icon name="md-map" color={tintColor} size={24} />
        )
      }
    },
    Profile: {
      screen: ProfileScreen,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <Icon name="md-person" color={tintColor} size={24} />
        )
      }
    }
  }
);

我要在它们之间通信的组件是MapScreen和EventsScreen。我在MapScreen中有一个数组,其中包含我希望能够从EventsScreen访问的标记。我已经研究了Redux和MobX,但是从我读到的内容来看,您将通过父级将数组传递给两个组件,就像MobX和Redux中的以下内容一样:

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Sibling1 array={array}/>
        <Sibling2 array={array}/>
      </View>
    );
  }
}

但是在我的示例中,除了底部导航器之外,这些组件没有共享父对象,但是我似乎无法通过该组件将变量传递给组件。

我可以通过两种方式访问​​同一阵列吗?

2 个答案:

答案 0 :(得分:1)

使用react-navigation,您可以通过将screenProps属性传递给Navigator组件,将同一个道具传递给多个屏幕:

例如:

const Navigator = createBottomTabNavigator({});
...
<Navigator screenProps={{ array: arrayToPassToAllScreen }} />
Now you can access the 'array' prop in every screen by doing so : `this.props.screenProps.array`

更新

这是您在文档中需要的:https://reactnavigation.org/docs/en/stack-navigator.html#navigator-props

答案 1 :(得分:1)

您必须将状态放置在这两个组件“上方”的某个位置。这可以通过拥有特定状态和平并通过道具向孩子提供此状态的普通父母来完成,也可以使用诸如React context,Redux或任何其他状态管理库之类的“全局”解决方案。

相关问题