在React Native屏幕之间传递数据(从屏幕A到屏幕B到屏幕C)

时间:2020-05-02 07:33:23

标签: reactjs react-native parameter-passing react-navigation

请考虑以下情形。 基本上,我们在MaterialTopTabNavigator中嵌套了StackNavigator

如何将数据从函数一直传递到MaterialTopTabNavigator。请注意,MaterialTopTabNavigator首先必须经过StackNavigator

file1.js

const[test,setTest] = useState('testing');
function moveToResults(){
    navigation.navigate('Results', test)
}

在这里,我们有一个简单的功能,该功能可使应用导航到其他屏幕,并传递test的状态。调用moveToResults()时,我们需要执行以下操作:

file2.js //注意,PostFun是StackNavigator的主页。

const Tab = createMaterialTopTabNavigator();

function PostFun({navigation}) {
  return (

         <Tab.Navigator 
            initialRouteName="Feed"
            activeColor="#e91e63"
            tabBarOptions={{
                labelStyle: {fontSize:12, color:"#faa19b"},
                tabStyle: {height:65, justifyContent: "flex-end"},
            }}
            style={styles.header}>
                <Tab.Screen name="Activity" component={FindFunActivity} />
                <Tab.Screen name="Event" component={FindFunEvent} />
        </Tab.Navigator>

  );
}

File2.js是`MaterialTopTabNavigator的开始,您可以看到此导航具有两个顶部标签(活动和事件)。

其中一个标签可能看起来像,这是我需要显示变量的地方:

file3.js

const FindFunEvent = (navigation) =>{
return(
<View>
    <Text>{navigation.getParam()}</Text>
</View>
)

}

问题

如何使test变量显示在FindFunEvent组件中?

这比任何东西都难解释,如果您愿意的话,这里是视觉效果。

Here is the link to a short video that goes over the issue

3 个答案:

答案 0 :(得分:2)

您可以通过将值作为组件的prop传递来实现此功能:

file1.js

const[test, setTest] = useState('testing');

function moveToResults(){
    navigation.navigate('Results', { test: test })
}

file2.js

const Tab = createMaterialTopTabNavigator();

function PostFun({ route, navigation }) {
  const { test } = route.params;

  return (
        <Tab.Navigator 
            initialRouteName="Feed"
            activeColor="#e91e63"
            tabBarOptions={{
                labelStyle: {fontSize:12, color:"#faa19b"},
                tabStyle: {height:65, justifyContent: "flex-end"},
            }}
            style={styles.header}
        >
          <Tab.Screen name="Activity">
              { (props) => <FindFunActivity {...props} myProp='test'  /> }
          </Tab.Screen>

          <Tab.Screen name="Event" component={() => <FindFunEvent test={test} />} />
        </Tab.Navigator>

  );
}

file3.js

const FindFunEvent = ({ test }) => {
  return(
    <View>
      <Text>{ test }</Text>
    </View>
  )
}

类似的示例可以在这里查看: https://snack.expo.io/UDHVnSUwK

答案 1 :(得分:0)

假设您要导航并将在屏幕A中获得的值传递到屏幕B和屏幕C。 你可以做这样的事情

ScreenA

this.props.navigation.navigate('ScreenB',
   {value: 'hi', });
}

屏幕B

this.props.navigation.navigate('ScreenC',
    this.props.route.params.value);
}

屏幕C

 this.props.route.params.value

答案 2 :(得分:0)

一种简单的方法是使用global.data。使用全局变量时,可以在应用程序中的任何位置使用它。但是,这不是理想的,因为在编程中使用全局不是最佳实践。我不确定要尝试的内容是否可行,如果不能,则可以使用global。

相关问题