还记得我们之前说过"我们讲参数的时候会详细说明"吗?是的,就是现在。
现在我们知道怎样创建一个包含若干路由的栈导航器,还知道了在路由之间跳转,现在让我们来看看跳转时怎样向路由传递数据。
有两点:
- 可以将参数放进对象中,作为navigation.navigate的第二个参数来向路由传递:
this.props.navigation.navigate('RouteName', { /* params go here */ })
- 在组件中读取参数:
this.props.navigation.getParam(paramName, defaultValue)
.
class 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>
);
}
}
你也可以直接接收参数对象: this.props.navigation.state.params。如果没有传递参数那么可能为null,所以通常使用getParams更加简便,不需要去处理null的情况。
如果你想直接通过props接收参数,比如this.props.itemId,你可以使用react-navigation-props-mapper.
总结
navigate
和push
接受可选的第二个参数来向目的路由传递参数,例如:this.props.navigation.navigate('RouteName', {paramName: 'value'})
.- 读取参数可以通过:
this.props.navigation.getParam
- 作为
getParam
的后备选择, 你也可以使用this.props.navigation.state.params
. 如果没有指定参数,得到的结果是null
.