一、主要構成
按使用形式主要分三部分:
1 、StackNavigator: 類似于普通的Navigator,屏幕上方導航欄
2 、TabNavigator: 相當于ios里面的TabBarController,屏幕下方的標簽欄
3 、DrawerNavigator: 抽屜效果,側邊滑出
二、使用
1、新建項目
react-native init ComponentDemo
2、在應用中安裝此庫
npm install --save react-navigation
3、測試TabNavigator、StackNavigator和DrawerNavigator
react-navigation 做 TarBar 布局和導航非常簡單方便,最好用的導航了
https://reactnavigation.org/docs/intro/
常用布局一般是首頁 4 個 TabBar 布局,直接用 TabNavigator 就行
import {StackNavigator, TabNavigator} from "react-navigation";
const MainScreenNavigator = TabNavigator({
Home: {
screen: Home,
navigationOptions: {
tabBar: {
label: '互助',
icon: ({tintColor}) => (
<Image
source={require('../images/home.png')}
style={[{tintColor: tintColor},styles.icon]}
/
>
),
},
}
},
Certificate: {
screen: Certificate,
navigationOptions: {
tabBar: {
label: '憑證',
icon: ({tintColor}) => (
<Image
source={require('../images/cert.png')}
style={[{tintColor: tintColor},styles.icon]}
/
>
),
},
}
},
}, {
animationEnabled: false, // 切換頁面時不顯示動畫
tabBarPosition: 'bottom', // 顯示在底端,android 默認是顯示在頁面頂端的
swipeEnabled: false, // 禁止左右滑動
backBehavior: 'none', // 按 back 鍵是否跳轉到第一個 Tab, none 為不跳轉
tabBarOptions: {
activeTintColor: '#0F9C00', // 文字和圖片選中顏色
inactiveTintColor: '#999', // 文字和圖片默認顏色
showIcon: true, // android 默認不顯示 icon, 需要設置為 true 才會顯示
indicatorStyle: {height: 0}, // android 中TabBar下面會顯示一條線,高度設為 0 后就不顯示線了, 不知道還有沒有其它方法隱藏???
style: {
backgroundColor: '#fff', // TabBar 背景色
},
labelStyle: {
fontSize: 12, // 文字大小
},
},
});
const styles = StyleSheet.create({
icon: {
height: 22,
width: 22,
resizeMode: 'contain'
}
});
然后頂層再用一個 StackNavigator ,把首頁和其它頁面嵌進去就行了。
StackNavigator 和 TabNavigator 是可以相互嵌套的,這樣就能從首頁 Tab 跳轉到其它頁面了
const App = StackNavigator({
Main: {
screen: MainScreenNavigator,
navigationOptions: {
header: {
title: '互助',
style: {
backgroundColor: '#fff'
},
backTitle: null
}
}
},
PlanDetail: {
screen: PlanDetail,
navigationOptions: {
header: {
style: {
backgroundColor: '#fff'
},
}
}
}
},{
mode: 'card', // 頁面切換模式, 左右是card(相當于iOS中的push效果), 上下是modal(相當于iOS中的modal效果)
headerMode: 'none', // 導航欄的顯示模式, screen: 有漸變透明效果, float: 無透明效果, none: 隱藏導航欄
});
//頁面跳轉、返回、傳參
const {navigate} = this.props.navigation;
<TouchableHighlight onPress={()=>{
navigate('PlanDetail',{name:'leslie',id:100});
}}>
// 返回上一頁
this.props.navigation.goBack();
//navigate 函數根據名字跳轉,還可以有第二個參數用于頁面之間傳遞參數
// 接收參數
export default class PlanDetail extends Component {
static navigationOptions = {
// title 可以這樣設置成一個函數, state 會自動傳過來
title: ({state}) => `${state.params.name}`,
};
componentDidMount() {
const {params} = this.props.navigation.state;
const id = [params.id](http://params.id);
}
// 通過 this.props.navigation.state.params 接收參數