在前边几个环节,我们学会了如何创建一个包含多个页面的导航器,并且学习了如何在页面间跳转的方法。接下来,我们将在这个环节学习如何在跳转页面时,同时附带参数。这主要有两个步骤:
将多个参数封装成一个对象,并将它作为navigate函数的第二个参数
1
this.props.navigation.navigate('RouteName', { /* params go here */ })
在屏幕组件中读取相应的参数
1
this.props.navigation.getParam(paramName, defaultValue)
以下是完整的代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51class HomeScreen extends React.Component {
render() {
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 */
this.props.navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
render() {
/* 2. Get the param, provide a fallback value if not available */
const { navigation } = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
const otherParam = navigation.getParam('otherParam', 'some default value');
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={() =>
this.props.navigation.push('Details', {
itemId: Math.floor(Math.random() * 100),
})}
/>
<Button
title="Go to Home"
onPress={() => this.props.navigation.navigate('Home')}
/>
<Button
title="Go back"
onPress={() => this.props.navigation.goBack()}
/>
</View>
);
}
}
重点:
1. 你也可以直接使用this.props.navigation.state.params来获取参数,但由于参数有可能为null,因此你需要进行额外的判断。例如:this.props.navigation.state.params.itemId
假如你希望直接this.props.itemId来获取页面传递的属性,而不是this.props.navigation.getParam这么复杂的写法,则可以使用社区开源的react-navigation-props-mapper包