felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

React Navigation 的 Screen 切换及路由配置 #140

Open felix-cao opened 5 years ago

felix-cao commented 5 years ago

Web 浏览器中,两个页面之间的切换,我们有两种方式:

一、HomeScreen 组件

在上一篇《React Native 入门 --- React Navigation 介绍》中,我们在 App.js 中有个组件 HomeScreen

// ... Other Code
import { View, Text, Button } from "react-native";
// ... Other Code

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}
// ... Other Code

上面的代码,我们在 onPress 中指定的匿名函数中直接使用了 navigation 对象的 navigate 函数。可以阅读 navigation 对象 API

需要说明的是,我们现在还没有在导航栈组件指定 navigate('Details')里的 Details 这个路由名,点击后将不会有任何事情发生,换句话说,navigate('Details') 函数中的Details必须是在导航栈组件的路由配置中已经存在的。

二、DetailsScreen 组件

下面我们来定义另外一个组件 DetailsScreen

// in App.js
// ... Other Code
class DetailsScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Button
          title="Go to Details... again"
          onPress={() => this.props.navigation.push('Details')}
        />
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate('Home')}
        />
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}
// ... Other Code

这里我们使用了 navigation 对象的三个方法 pushnavigategoBack三个方法

三、配置路由

现在我们需要利用createStackNavigator创建导航栈组件, 并传递路由配置参数。

// ... Other Code
const routeConfig =  {
  Home: {
    screen: HomeScreen
  },
  Details: {
    screen: DetailsScreen,
  },
 };

const AppNavigator = createStackNavigator(
 routeConfig,
 { 
  initialRouteName: 'Home' 
 }
);
// ... Other Code

createStackNavigator

createStackNavigator(RouteConfigs, StackNavigatorConfig);

可以优化一下:

// ... Other Code

const routeConfig =  {
  Home: HomeScreen,
  Details: DetailsScreen
};
const AppNavigator = createStackNavigator(
 routeConfig,
 { initialRouteName: 'Home' }
);
// ... Other Code

snacks 跑一把

最后把这些代码放到 snacks 中跑一吧.

四、什么是 Screen Component

Screen Component 是用在路由配置中的组件,本文中的 HomeScreenDetailsScreen 就是 Screen Component,命名会习惯(convention)的加上 Screen 这个后缀。

所以我们要明白:

1)、 Screen Component 用于在 Stack Navigation 中进行路由配置的。 2)、然后在Screen Component中,我们才能使用 this.props.navigation,否则会提示 exceptions "undefined is not an object".

Reference