導(dǎo)航到一個(gè)新屏幕
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
屬性被傳遞到每一個(gè) screen component (definition) (more about this later in "The navigation prop in depth"). - 每次你調(diào)用
push
,都會(huì)添加一個(gè)新的路由到導(dǎo)航堆棧。當(dāng)你調(diào)用navigate
時(shí),它首先會(huì)嘗試找到同名的現(xiàn)有路由,只有在堆棧上還沒有新路由時(shí)才會(huì)推送新路由。
返回屏幕
navigation.goBack(); // 返回上一個(gè)屏幕
navigation.popToTop(); // 返回第一個(gè)屏幕
屏幕導(dǎo)航時(shí)傳遞參數(shù)
方法:
- 通過將參數(shù)作為導(dǎo)航的第二個(gè)參數(shù)放在一個(gè)對象中,將它們傳遞給路由。
navigation.navigate('RouteName', { /* params go here */ })
- 讀取屏幕組件中的參數(shù):
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;
更新參數(shù)
navigation.setParams({
query: 'someText',
});
注意:避免使用setParams來更新屏幕選項(xiàng),如標(biāo)題等。如果您需要更新選項(xiàng),請使用setOptions。
初始化屏幕參數(shù)
<Stack.Screen
name="Details"
component={DetailsScreen}
initialParams={{ itemId: 42 }}
/>
向前一個(gè)屏幕傳遞參數(shù)
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,
});
}}
/>
</>
);
}