React Native使用react-navigation实现
一、介绍
react-navigation是RN官方推荐使用的一个单独的导航库,关于该库,官网已经写得很详细了:(https://reactnavigation.org/docs/zh-Hans/getting-started.html)
二、安装
1、安装react-navigation
在命令行中敲入(yarn默认--save,因此不用加上)
yarn add react-navigation
或
npm i react-navigation --save
2、安装react-native-gesture-handler
yarn add react-native-gesture-handler
或
npm install --save react-native-gesture-handler
3、链接依赖
react-native link
这行代码会将你之前装过但没有链接过的库都链接一遍,如果你只想链接本文介绍的react-navigation :
react-native link react-native-gesture-handler
三、使用
以下代码均属于同一个js文件
First组件:
class First extends React.Component{
constructor(props){
super(props)
this.state = {};
}
_press=()=>{
this.props.navigation.navigate('Detail')
}
render(){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<Text>First Page!</Text>
<Button
title="test"
onPress={this._press}
/>
</View>
)
}
}
Second组件:
class Second extends React.Component{
constructor(props){
super(props)
this.state = {};
}
render(){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<Text>Second Page!</Text>
</View>
)
}
}
Detail组件:
class Detail extends React.Component{
constructor(props){
super(props)
this.state={}
}
render(){
return(
<View>
<Text>this is detail</Text>
</View>
)
}
}
完整代码:
import React, { Component } from 'react';
import {
Text,
StyleSheet,
View,
Button
} from 'react-native';
import {
createBottomTabNavigator,
createAppContainer,
createStackNavigator,
} from 'react-navigation';
class First extends React.Component{
constructor(props){
super(props)
this.state = {};
}
_press=()=>{
this.props.navigation.navigate('Detail')
}
render(){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<Text>First Page!</Text>
<Button
title="test"
onPress={this._press}
/>
</View>
)
}
}
class Second extends React.Component{
constructor(props){
super(props)
this.state = {};
}
render(){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<Text>Second Page!</Text>
</View>
)
}
}
class Detail extends React.Component{
constructor(props){
super(props)
this.state={}
}
render(){
return(
<View>
<Text>this is detail</Text>
</View>
)
}
}
const TabNavigator = createBottomTabNavigator({
First : First,
Second : Second
})
const Stack = createStackNavigator({
Tab : TabNavigator,
Detail : Detail
})
export default createAppContainer(Stack)
四、注意项
1、
关于StackNavigation和TabNavigation的顺序问题(我就曾经搞混过..)
Z0F0J8XKA0FZPVP~A%6L4JH.jpg
事实上TabNavigation是一个包含了两个页面(First、Second)的组件,应该将它当作页面包含进StackNavigation,然后将StackNavigation作为最底部的组件。
如果你发现你的项目在跳转进子页面之后,还保留着TabNavigation的菜单栏(图中红圈圈着的),那你需要检查一下是不是顺序出了问题
2、
有用过RN写过东西的应该就能深深体会到,每一个方法(方法体里涉及到操作state)都需要绑定作用域,通常有三个方法
1.在构造函数constructor里面进行绑定
2.在调用方法时绑定
3.(推荐)将方法定义写成箭头函数 :
_press=()=>{
this.props.navigation.navigate('Detail')
}
因为箭头函数里面根本没有自己的this,而是引用外层的this,这就相当于在定义方法时直接绑定了作用域
五、结语
本文简单介绍了react-navigation中TabNavigation和StackNavigation的用法,希望能帮助到刚入门RN的人