ps:有一些代码演示效果只能在官网中看到~
手机导航器,你好
让我们一起使用react的导航组件在安卓和IOS上建立一个简单的聊天应用。
安装
# Create a new React Native App
react-native init SimpleApp
cd SimpleApp
# Install the latest version of react-navigation from npm
npm install --save react-navigation
# Run the new app
react-native run-android # or:
react-native run-ios
确定你已经成功的看到一个空的初始项目可以运行在IOS或者安卓上。
bare-project
我们想在IOS和安卓上分享同一份代码,所以我们删除index.ios.js
和 index.android.js
原来里面的代码,然后使用import './App';
。
现在让我们创立一个新的文件并命名为App.js
,通过使用它来启动我们的项目.
Stack Navigator 介绍
我们想用StackNavigator
在我们的app上,因为我们想在概念上通过栈的形式去使用导航,通过栈的形式,每个一新的场景(页面)将放在栈顶,在后退的时候我们将移除栈顶的场景(页面)。
让我们用一个场景(页面)去开始吧:
import React from 'react';
import {
AppRegistry,
Text,
} from 'react-native';
import { StackNavigator } from 'react-navigation';
class HomeScreen extends {
static navigationOptions = {
title: 'Welcome',
};
render() {
return <Text>Hello, Navigation!</Text>;
}
}
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
});
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
现在一个相同的页面应该会出现在iphone和安卓应用上
first-screen
增加一个新的场景/页面
在 HomeScreen
创建一个按钮去连接我们的第二个页面:
class HomeScreen extends {
static navigationOptions = {
title: 'Welcome',
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Hello, Chat App!</Text>
<Button
onPress={() => navigate('Chat', { user: 'Lucy' })}
title="Chat with Lucy"
/>
</View>
);
}
}
现在让我们创建一个聊天场景/页面去显示name
这个路由中传递过来的参数。
class ChatScreen extends {
static navigationOptions = {
// Nav options can be defined as a function of the navigation prop:
title: ({ state }) => `Chat with ${state.params.user}`,
};
render() {
// The screen's current route is passed in to `props.navigation.state`:
const { params } = this.props.navigation.state;
return (
<View>
<Text>Chat with {params.user}</Text>
</View>
);
}
}
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
Chat: { screen: ChatScreen },
});
现在你可以通过导航器跳转到新的场景/页面,以及返回
first-navigation