Open felix-cao opened 5 years ago
在 《React Navigation 的 Screen 切换及路由配置 》中,我们聊了 Screen 切换,同 WEB 中 a 的页面跳转一样,都是可以带参数的。本篇来学习一下Screen 切换中的参数传递。需要掌握下面两个知识点:
Screen
WEB
a
this.props.navigation.navigate('RouteName', { /* params go here */ })
this.props.navigation.getParam(paramName, defaultValue)
在 HomeScreen 中点击 Button 按钮时,传递给名字为 Details 的路由两个参数,itemId 和 otherParam
HomeScreen
Button
Details
itemId
otherParam
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> ); } }
在 DetailsScreen 中读取这两个参数, 并显示出来
DetailsScreen
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'); // const otherParam = this.props.navigation.state.params.otherParam; 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> ); } }
在 snack 上跑一把
snack
序列化JSON
this.props.navigation.state.params
getParam
this.props.itemId
this.props.navigation.getParam('itemId')
React Native
在 《React Navigation 的 Screen 切换及路由配置 》中,我们聊了
Screen
切换,同WEB
中a
的页面跳转一样,都是可以带参数的。本篇来学习一下Screen
切换中的参数传递。需要掌握下面两个知识点:this.props.navigation.navigate('RouteName', { /* params go here */ })
this.props.navigation.getParam(paramName, defaultValue)
一、传递参数
在
HomeScreen
中点击Button
按钮时,传递给名字为Details
的路由两个参数,itemId
和otherParam
二、读取参数
在
DetailsScreen
中读取这两个参数, 并显示出来在
snack
上跑一把序列化JSON
方式。为了方便状态留存(state persistance)处理this.props.navigation.state.params
去读取接收参数,但建议使用getParam
this.props.itemId
代替this.props.navigation.getParam('itemId')
,建议安装使用React Native
社区提供的 react-navigation-props-mapper