導航到一個新屏幕
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
}
-
navigation
- 在native stack navigator
中navigation
屬性被傳遞到每一個 screen component (definition) (more about this later in "The navigation prop in depth"). - 每次你調用
push
,都會添加一個新的路由到導航堆棧。當你調用navigate
時,它首先會嘗試找到同名的現有路由,只有在堆棧上還沒有新路由時才會推送新路由。
返回屏幕
navigation.goBack(); // 返回上一個屏幕
navigation.popToTop(); // 返回第一個屏幕
屏幕導航時傳遞參數
方法:
- 通過將參數作為導航的第二個參數放在一個對象中,將它們傳遞給路由。
navigation.navigate('RouteName', { /* params go here */ })
- 讀取屏幕組件中的參數:
route.params
。
onPress={() => {
/* 1. Navigate to the Details route with params */
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
function DetailsScreen({ route, navigation }) {
/* 2. Get the param */
const { itemId, otherParam } = route.params;
更新參數
navigation.setParams({
query: 'someText',
});
注意:避免使用setParams來更新屏幕選項,如標題等。如果您需要更新選項,請使用setOptions。
初始化屏幕參數
<Stack.Screen
name="Details"
component={DetailsScreen}
initialParams={{ itemId: 42 }}
/>
向前一個屏幕傳遞參數
function HomeScreen({ navigation, route }) {
React.useEffect(() => {
if (route.params?.post) {
// Post updated, do something with `route.params.post`
// For example, send the post to the server
}
}, [route.params?.post]);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Create post"
onPress={() => navigation.navigate('CreatePost')}
/>
<Text style={{ margin: 10 }}>Post: {route.params?.post}</Text>
</View>
);
}
function CreatePostScreen({ navigation, route }) {
const [postText, setPostText] = React.useState('');
return (
<>
<TextInput
multiline
placeholder="What's on your mind?"
style={{ height: 200, padding: 10, backgroundColor: 'white' }}
value={postText}
onChangeText={setPostText}
/>
<Button
title="Done"
onPress={() => {
// Pass and merge params back to home screen
navigation.navigate({
name: 'Home',
params: { post: postText },
merge: true,
});
}}
/>
</>
);
}