一聚教程网:一个值得你收藏的教程网站

热门教程

官方推荐react-navigation的具体使用详解

时间:2022-06-25 16:07:21 编辑:袖梨 来源:一聚教程网

看了官方文档的导航器对比,发现现在主推的方案是一个单独的导航库react-navigation,据说它的使用十分简单。我就写个demo,试了一下。

一、主要构成

按使用形式主要分三部分:

  1. StackNavigator: 类似于普通的Navigator,屏幕上方导航栏
  2. TabNavigator: 相当于ios里面的TabBarController,屏幕下方的标签栏
  3. DrawerNavigator: 抽屉效果,侧边滑出

二、使用

1.新建项目

react-native init ComponentDemo

2. 在应用中安装此库

npm install --save react-navigation

安装完发现是beta版本(v1.0.0-beta.7) ,竟然有坑?!一会儿我们会详细说这个坑~

3.测试TabNavigator、StackNavigator和DrawerNavigator

(1)新建HomePage.js

import React from 'react';
import {
  StyleSheet,
  View,
  Text,
  Button,
  Image
} from 'react-native';

import {
  StackNavigator,
  TabNavigator
} from 'react-navigation';

import ChatScreen from './ChatScreen';
import MinePage from './MinePage';

class HomePage extends React.Component{

  static navigationOptions={
    title: '首页',//设置标题内容
    header:{
      backTitle: ' ',//返回按钮标题内容(默认为上一级标题内容)
    }
  }

  constructor(props) {
    super(props);
  }

  render() {
    const {navigate} = this.props.navigation;
    return (
      
        Hello, Navigation!
        

(2)新建ChatScreen.js

import React from 'react';
import {
  Button,
  Image,
  View,
  Text
} from 'react-native';

class ChatScreen extends React.Component {
  static navigationOptions = {
    title:'聊天',
  };

  render() {
    const {params} = this.props.navigation.state;
    return (
    
      Chat with {params.user}

    

    );
  }
}
export default ChatScreen;

(3)新建MinePage.js

import React,{Component} from 'react';
import {
  Button,
  Image,
  View,
  Text,
  StyleSheet
} from 'react-native';

import {
  DrawerNavigator
} from 'react-navigation';

import MyNotificationsScreen from './MyNotificationsScreen';

class MinePage extends Component{
  static navigationOptions = {
     title:'我的',
     drawerLabel: '我的',
    // Note: By default the icon is only shown on iOS. Search the showIcon option below.
     drawerIcon: ({ tintColor }) => (
     
   ),
  };
  render(){;
    return(
      
        Sybil
        

(4)编写MyNotificationsScreen.js

import React from 'react';
import {
  StyleSheet,
  View,
  Text,
  Button,
  Image
} from 'react-native';

class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    title:'通知',
    drawerLabel: '通知',
    drawerIcon: ({ tintColor }) => (
      
    ),
  };

  render() {
    return (
       
        

(5)运行

报错啦?这就是上面我们所说的坑~

什么原因呢?原来是测试版的bug,在目录中找到node_modules/react-navigation/src/views/Header.js的第12行,删除它就OK了~

Ps:遗憾的是这个错误我没有留图啊~在我即将发表这篇文章的时候,最新版已经变为(v1.0.0-beta.9)了,最新版已经将上述的bug修改了!

好了,再次运行~

上一个动态效果图:

想详细了解React Navigation,可以阅读这一篇英文的入门文档,希望对你们有所帮助~

热门栏目