1 回答

TA貢獻1806條經(jīng)驗 獲得超8個贊
以下是如何將狀態(tài)從 A、B、C 傳遞到 D。您只需在導航到下一個 Screen 路由時將父級的狀態(tài)作為參數(shù)傳遞給下一個 Screen 路由,然后您就可以借助以下命令訪問這些參數(shù)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;
添加回答
舉報