react-navigation stackNavigator组件官方文档翻译

安装

#Install the latest version of react-navigation from npm 
npm install --save react-navigation

StackNavigator是一个用到了栈概念的导航器,每一个新页面会被放到栈顶,回退页面会移除栈顶页面。

下面是一个单页示例。

Stack Navigator单页

import React from 'react';
import {
  AppRegistry,
  Text,
} from 'react-native';
import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    return Hello, Navigation!;
  }
}

const SimpleApp = StackNavigator({
  Home: { screen: HomeScreen },
});

AppRegistry.registerComponent('SimpleApp', () => SimpleApp);

页面的标题(title)在默认属性 navigationOptions里得到配置,这也是用来配置navigator页面展示效果的地方。

react-navigation stackNavigator组件官方文档翻译_第1张图片
singlePage_RN.png

下面试试添加一个叫做chatScreen的新页面,

class ChatScreen extends React.Component {
  static navigationOptions = {
    title: 'Chat with Lucy',
  };
  render() {
    return (
      
        Chat with Lucy
      
    );
  }
}

在HomeScreen组件我们可以添加一个按钮链接到ChatScreen,通过设置名为Chat的路由

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      
        Hello, Chat App!
        

我们使用传入页面的navigation属性给navigate函数去跳转到目标页面(这里是ChatScreen),但页面必须都添加进StackNavigator中:

const SimpleApp = StackNavigator({
  Home: { screen: HomeScreen },
  Chat: { screen: ChatScreen },
});

页面间传参,在跳转路由中设置参数,在被跳转页面里就可以接受参数

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      
        Hello, Chat App!
        
class ChatScreen extends React.Component {
  // Nav options can be defined as a function of the screen's props:
  static navigationOptions = ({ navigation }) => ({
    title: `Chat with ${navigation.state.params.user}`,
  });
  render() {
    // The screen's current route is passed in to `props.navigation.state`:
    const { params } = this.props.navigation.state;
    return (
      
        Chat with {params.user}
      
    );
  }
}

你可能感兴趣的:(react-navigation stackNavigator组件官方文档翻译)