1 回答
TA贡献1806条经验 获得超8个赞
以下是如何将状态从 A、B、C 传递到 D。您只需在导航到下一个 Screen 路由时将父级的状态作为参数传递给下一个 Screen 路由,然后您就可以借助以下命令访问这些参数route。
import React, { useState } from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function A({ navigation }) {
const [fromA, setFromA] = useState('From A');
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>A Screen</Text>
<Button
title="Go to B"
onPress={() => navigation.navigate('B', { fromA: fromA })}
/>
</View>
);
}
function B({ navigation, route }) {
const [fromB, setFromB] = useState('From B');
const { fromA } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>A Screen</Text>
<Button
title="Go to C"
onPress={() => navigation.navigate('C', { fromA: fromA, fromB: fromB })}
/>
</View>
);
}
function C({ navigation, route }) {
const [fromC, setFromC] = useState('From C');
const { fromA, fromB } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>A Screen</Text>
<Button
title="Go to D"
onPress={() =>
navigation.navigate('D', { fromA: fromA, fromB: fromB, fromC: fromC })
}
/>
</View>
);
}
function D({ navigation, route }) {
const { fromA, fromB, fromC } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>D Screen</Text>
<Text>From Screen A: {fromA}</Text>
<Text>From Screen B: {fromB}</Text>
<Text>From Screen C: {fromC}</Text>
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="A">
<Stack.Screen name="A" component={A} />
<Stack.Screen name="B" component={B} />
<Stack.Screen name="C" component={C} />
<Stack.Screen name="D" component={D} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
添加回答
举报