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 是如何工做的。