react提供了router路由react-router-dom,ReactNative为了能够在移动端有更多的路由使用体验,专门开发了路由系统.
官方网址:https://reactnavigation.org/
使用RN的路由,需要在项目包安装并且编译成apk才能使用
1、安装:npm install @react-navigation/native
2、使用:
NavigationContainer:路由容器
Stack.Navigator:栈式导航 一个匹配一个页面组件
screenOptions:配置每个页面的标题栏
Stack.Screen:路由名称 name component 组件名称(默认显示第一个)
options:自定义配置
import * as React from 'react';
import {View, Text} from 'react-native';
// 路由容器
import {NavigationContainer} from '@react-navigation/native';
// 栈式导航
import {createNativeStackNavigator} from '@react-navigation/native-stack';
//引入组件
import APage from './pages/APage';
import BPage from './pages/BPage';
import CPage from './pages/CPage';
import DPage from './pages/DPage';
// 创建一个栈式导航
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerStyle: {backgroundColor: 'red'},
headerTitleStyle: {color: 'white'},
}}>
<Stack.Screen
name="A"
component={APage}
options={{
headerTitle: '首页',
headerStyle: {backgroundColor: 'orangered'},
}}
/>
<Stack.Screen name="B" component={BPage} />
<Stack.Screen name="C" component={CPage} />
<Stack.Screen name="D" component={DPage} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
3、跳转和传参:
路由会向组件props注入两个属性:
① navigation:包含了操作路由的方法,跳转方法
② route:包含路由相关的传参
export default class APage extends Component {
render() {
const {push} = this.props.navigation;
return (
<View>
<TouchableOpacity onPress={() => push('C')}>
<Text>跳转到C页面</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => push('D', {name:'react',msg:'react'})}>
<Text>跳转到D页面</Text>
</TouchableOpacity>
</View>
);
}
}
接收A传递的参数:this.props.route.params
setOptions:动态设置标题栏
export default class DPage extends Component {
componentDidMount() {
const {setOptions} = this.props.navigation;
const {name, msg} = this.props.route.params;
setOptions({
headerTitle: name,
});
}
render() {
const {name, msg} = this.props.route.params;
return (
<View>
<Text>{msg}</Text>
<Text>{name}</Text>
</View>
);
}
}