react-navigation 做 TarBar 布局和导航非常简单方便,最好用的导航了。
https://reactnavigation.org/docs/intro/
常用布局一般是首页 4 个 TabBar 布局,直接用 TabNavigator 就行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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 跳转到其它页面了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const App = StackNavigator({ Main: { screen: MainScreenNavigator, navigationOptions: { header: { title: '互助', style: { backgroundColor: '#fff' }, backTitle: null } } }, PlanDetail: { screen: PlanDetail, navigationOptions: { header: { style: { backgroundColor: '#fff' }, } } } }); AppRegistry.registerComponent('QQHZ_RN', () => App); |
页面跳转、返回、传参
1 2 3 4 5 6 7 |
const {navigate} = this.props.navigation; <TouchableHighlight onPress={()=>{ navigate('PlanDetail',{name:'leslie',id:100}); }}> // 返回上一页 this.props.navigation.goBack(); |
navigate 函数根据名字跳转,还可以有第二个参数用于页面之间传递参数
接收参数
1 2 3 4 5 6 7 8 9 10 |
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; } |
通过 this.props.navigation.state.params 接收参数