rn 路由传参、navigation传参
路由传参:
(1)传参数
(1)发送
函数式传递
function xx({navigation})
{
...
//发送
{navigation.navigate('路由名',{键值对})}
}
路由声明处传递
<Stack.Screen name="xx" component={x} initialParams={
{键值对}}/>
(2)接收
1、函数式组件
function xx({navigation,route})
{
...
//接收
{JSON.stringify(route.params.键名)}
}
2、类组件
export default class xx extends Component{
...
const {route} = this.props
...
{JSON.stringify(route.params.键名)}
}
其中:
(1)接收参数最好使用JSON.stringify将参数序列化成字符串(官方推荐),能做到深度链接
(2)可传参数{route.params?.键名}; 当参数存在时才显示,多用于下一个屏幕传递到上一个屏幕
navigation传参:
this.props.navigation.setParams({键值对});
this.props.navigation.getParam('键名');
代码示例:
import 'react-native-gesture-handler';
import React,{ Component} from 'react'
import { Text,View,StyleSheet,Button,ScrollView} from 'react-native'
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import A from './App21'
function Home({ navigation,route }){
return (
<View style={ { flex:1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Text>{ route.params?.address}</Text>
<Button
title="Go to Details"
//导航,相当于go,相当页面不会放进栈里
onPress={ () =>navigation.navigate('Details',{ name:'jeff',pass:'123'})}
color='red'
></Button>
<Button
title="Go to A"
//push会将路由放进堆栈里即使是相同页面
onPress={ () => navigation.navigate('A',{ id:'2'})}
/>
</View>
);
}
function DetailsScreen({ navigation,route}) {
return (
<View style={ { flex:1,alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>{ JSON.stringify(route.params.name)}</Text>
<Text>{ JSON.stringify(route.params.pass)}</Text>
<Text>{ JSON.stringify(route.params.sex)}</Text>
<Button
title="Go to Details... again"
//push会将路由放进堆栈里即使是相同页面
onPress={ () => navigation.push('Details')}
/>
<Button
title="Go Back"
//push会将路由放进堆栈里即使是相同页面
onPress={ () => navigation.navigate('Home',{ address:'heart'})}
/>
</View>
);
}
function New({ navigation}) {
return (
<View style={ { flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>New Screen</Text>
</View>
);
}
export default class App extends Component{
render(){
const Stack = createStackNavigator();
return (
<>
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={ Home} options={ { title: 'Overview' }}/>
<Stack.Screen name="Details" component={ DetailsScreen} initialParams={ { sex:'female'}}/>
<Stack.Screen name="New" component={ New} />
<Stack.Screen name="A" component={ A} />
</Stack.Navigator>
</NavigationContainer>
</>
);
}
}
类组件:
import React,{ Component} from 'react'
import { View,Text,StyleSheet,Button} from 'react-native'
import FontAwesome from 'react-native-vector-icons/dist/FontAwesome'
export default class App extends Component{
render(){
const { navigation,route}=this.props
return(
<>
<Text>哈哈哈</Text>
<Text>{ route.params.id}</Text>
<Button
title='go details'
onPress={ ()=>navigation.navigate('Details')}
/>
</>
)
}
}
还没有评论,来说两句吧...