现在,我们知道如何创建配置导航器,并且如何在路由页面之间跳转。现在让我们来探讨一下当我们跳转页面的时候如何传递参数。
关于这个有两点需要强调:
- 我们可以将参数封装成一个对象,然后将这个对象作为navigation.navigate方法的第二个参数,从而实现跳转的时候传递参数过去。
- 使用route.params方法读取传递过来的参数。
我们建议你传递过来的参数是JSON序列化的。
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
/* 1. Navigate to the Details route with params */
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
function DetailsScreen({ route, navigation }) {
/* 2. Get the param */
const { itemId } = route.params;
const { otherParam } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}</Text>
<Button
title="Go to Details... again"
onPress={() =>
navigation.push('Details', {
itemId: Math.floor(Math.random() * 100),
})
}
/>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
);
}
在路由页面上也可以更新这些参数,navigation.setParams方法就是用来更新这些参数的。你可以在API中查找setParams方法来获取更多相关信息
你也可以设置所传参数的默认值,当跳转页面时没有指定这些参数的值,那么他们就会使用默认值。你也可以将默认值和你传递的参数混合使用。参数的默认值可以在 initialParams属性中指定。
<Stack.Screen
name="Details"
component={DetailsScreen}
initialParams={{ itemId: 42 }}
/>
参数可以将数据传递给一个新的路由页面,同时也可以将数据回传给先前路由的页面。例如,你有一个路由页面,该页面有一个创建帖子的按钮,这个按钮可以打开一个新的页面来创建帖子,在创建完帖子之后,你想将帖子的一些数据回传给先前的页面。
你可以使用navigate来实现这个需求,如果路由已经在堆栈中存在了,他们他看起来就像goBack一样。你可以将数据绑定到nvigate的params回传给上一页。
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 params back to home screen
navigation.navigate('Home', { post: postText });
}}
/>
</>
);
}
这样,当你点击Done按钮后,home页面的route.params将会被更新并刷新文本。
总结
- navigate和push都可以接受一个可选的参数,以便于你向路由的页面传递参数。比如:navigation.navigate('RouteName',{patamName:'value'}).
- 你可以在路由页面中用route.params来读取传递过来的参数
- 你可以通过调用navigation.setParams来更新路由页面的参数。
- 参数的默认值可以通过Screen的initialParams来指定。