React Native (一)

创建一个导航器

这个导航器实现的功能类似于浏览器的前进后退跳转,没有tab导航。

创建一堆页面用来跳转

首先创建几个页面


// as long as you use react native related component you need next line
import React, { Component } from 'react'
import {View, Text, StyleSheet, Button} from 'react-native'
/*
in object this.props, navigation is very important, go(), navigate() often use
navigation = state + setParams + other
params is in state
so you may write this code frequently

const {navigation} = this.props
const {setParams, state} = navigation
const {params} = state
*/
export default class Home extends Component{
  static navigationOptions = {
    title: "Home",
    headerBackTitle: "回首页"
  }
  render(){
    const {navigation} = this.props
    return (
      
        Welcome to Home Page!
        

其他的页面类似。

创建导航

// to create a navigator, these code is necessary
import React, {Component} from "react"
import {View, Text, Button} from 'react-native'
import {createStackNavigator, createAppContainer} from "react-navigation"

// then, import your pages
import HomePage from '../pages/Home.js'
import Page1 from '../pages/Page1.js'
import Page2 from '../pages/Page2.js'
import Page3 from '../pages/Page3.js'
import Page4 from '../pages/Page4.js'

// create a navigator by createStackNavigator, means stack router
// I create three pages use none config, dynamic config and static config
// this api need a config object like this:

const AppNavigator = createStackNavigator({
  Home: {
    screen: HomePage,
    navigationOptions: {}
    // you can set navigationOptions at here
    // you can set navigationOptions at HomePage also
  },
  Page1: {
    screen: Page1,
    navigationOptions: ({ navigation } ) => { // navigation was in props, take it out by use deconstruction assignment
      title: `${navigation.state.params.name}` // dynamic navigation data
    }
  },
  Page2: {
    screen: Page2,
    // here can static appoint what the title it show
    navigationOptions: {
      title: "This is Page2" // static navigation data
    }
  },
  Page3: {
    screen: Page3,
    navigationOptions: (props) => {
      const { navigation } = props
      const { state, setParams } = navigation
      const { params } = state
      return {
        title: params.title ? params.title : "This is Page3",
        headerRight: (
          

接下来的事情就是, 将这个导航器导出,在index.js中导入并且使用。

// must do this, do not ask me why
const AppContainer = createAppContainer(AppNavigator)
export default AppContainer

然后, 在index.js里面

// ./navigator/navigator.js is our navogator, that is the above code
import {AppRegistry} from 'react-native';
// import App from './App';
import App from './navigator/navigator.js'
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

react-native run-ios. 神奇的事情发生了。

你可能感兴趣的:(React Native (一))