React Native 包管理器同时用到了 node
和 watchman
, 并采用了同为 Facebook 出品的 flow
做为类型检查库,所以咱们将在 macOS 下使用 Homebrew 进行相关依赖的安装。html
安装 Homebrewnode
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
复制代码
安装 React Native 依赖react
$ brew install node
$ brew install watchman
$ brew install flow
复制代码
== 若是在安装过程当中遇到问题,可尝试更新 brew 和相关依赖包 ==android
$ brew update
$ brew upgrade
复制代码
安装 React Nativeios
$ npm install -g react-native-cli
复制代码
针对不一样平台安装 Xcode 或 Android Studio 开发环境git
使用 React Native 命令行工具建立一个模板工程github
$ react-native init HelloReactNative
复制代码
按项目建立的成功提示运行应用objective-c
To run your app on iOS:
cd /Users/Binboy/Desktop/HelloReactNative
react-native run-ios
- or -
Open /Users/Binboy/Desktop/HelloReactNative/ios/HelloReactNative.xcodeproj in Xcode
Hit the Run button
To run your app on Android:
Have an Android emulator running (quickest way to get started), or a device connected
cd /Users/Binboy/Desktop/HelloReactNative
react-native run-android
复制代码
== 若运行出错,可尝试在工程目录下从新运行 npm install
和 npm start
==npm
登陆开发者帐号 -> 注册 iOS 设备 UUID -> 在 AppDelegate.m
中配置 React Native 文件地址 jsCodeLocation
react-native
摸索一下命令行工具生成的默认工程项目代码吧~
AppDelegate.m
中声明根视图 RCTRootView
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"HelloReactNative"
initialProperties:nil
launchOptions:launchOptions];
复制代码
index.ios.js
中,代码最后一行能够看到其中注册了一个相同名字的组件AppRegistry.registerComponent('HelloReactNative', () => HelloReactNative);
复制代码
index.ios.js
文件的开头import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
复制代码
开发过程当中,咱们须要导入所需的每个组件或模块,包括像 AppRegistry
和 StyleSheet
这样基本的库函数模块。
export default class HelloReactNative extends Component {
render() {
return (
<View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View>
);
}
}
复制代码
熟悉HTML这样的结构化标记语言的话,这段代码不难理解,表达了视图中的组件结构
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
复制代码
React Native 中全部样式都采用样式对象
来代替传统样式表,一般使用 StyleSheet
库来建立组件样式。
大体熟悉了默认示例工程的文件结构与代码组织,那么接下来咱们就将作点儿有趣的尝试来实现一些简单的小功能,看看 React Native 是如何工做的。