搭建开发环境

欢迎使用React Native!这篇文档会帮助你搭建基本的React Native开发环境。如果你已经搭好了环境,那么可以尝试一下编写Hello World

根本你所使用的操作系统、针对的目标平台不同,具体步骤有所不同。如果想同时开发iOS和Android也没问题,你只需要先选一个平台开始,另一个平台的环境搭建只是稍有不同。

目标平台: iOS Android 开发平台: Mac Linux Windows

译注:如果阅读完本文档后还碰到很多环境搭建的问题,我们建议你还可以再看看由本站提供的环境搭建视频教程windows环境搭建文字教程、以及常见问题

安装

必需的软件

Homebrew

Homebrew, Mac系统的包管理器,用于安装NodeJS和一些其他必需的工具软件。

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

译注:在Max OS X 10.11(El Capitan)版本中,homebrew在安装软件时可能会碰到/usr/local目录不可写的权限问题。可以使用下面的命令修复:

sudo chown -R `whoami` /usr/local

Node

使用Homebrew来安装Node.js.

React Native需要NodeJS 4.0或更高版本。本文发布时Homebrew默认安装的是6.x版本,完全满足要求。

brew install node

React Native的命令行工具(react-native-cli)

React Native的命令行工具用于执行创建、初始化、更新项目、运行打包服务(packager)等任务。

npm install -g react-native-cli

如果你看到EACCES: permission denied这样的权限报错,那么请参照上文的homebrew译注,修复/usr/local目录的所有权:

sudo chown -R `whoami` /usr/local

Xcode

React Native目前需要Xcode 7.0 或更高版本。你可以通过App Store或是到Apple开发者官网上下载。这一步骤会同时安装Xcode IDE和Xcode的命令行工具。

虽然一般来说命令行工具都是默认安装了,但你最好还是启动Xcode,并在Xcode | Preferences | Locations菜单中检查一下是否装有某个版本的Command Line Tools。Xcode的命令行工具中也包含一些必须的工具,比如git等。

推荐安装的工具

Watchman

Watchman是由Facebook提供的监视文件系统变更的工具。安装此工具可以提高开发时的性能(packager可以快速捕捉文件的变化从而实现实时刷新)。

brew install watchman

Flow

Flow是一个静态的JS类型检查工具。译注:你在很多示例中看到的奇奇怪怪的冒号问号,以及方法参数中像类型一样的写法,都是属于这个flow工具的语法。这一语法并不属于ES标准,只是Facebook自家的代码规范。所以新手可以直接跳过(即不需要安装这一工具,也不建议去费力学习flow相关语法)。

brew install flow

Nuclide

Nuclide(此链接需要科学上网)是由Facebook提供的基于atom的集成开发环境,可用于编写、运行调试React Native应用。

点击这里阅读Nuclide的入门文档

译注:我们更推荐使用WebStormSublime Text来编写React Native应用。

测试安装

react-native init AwesomeProject
cd AwesomeProject
react-native run-ios

你也可以在Nuclide中打开AwesomeProject文件夹 然后运行,或是双击ios/AwesomeProject.xcodeproj文件然后在Xcode中点击Run按钮。

修改项目

现在你已经成功运行了项目,我们可以开始尝试动手改一改了:

  • 使用你喜欢的编辑器打开index.ios.js并随便改上几行。
  • 在iOS Emulator中按下⌘-R就可以刷新APP并看到你的最新修改!

完成了!

恭喜!你已经成功运行并修改了你的第一个React Native应用。

接下来

嵌入到现有原生应用

Create your actual React Native components in JavaScript.

  1. Add a new event handler that creates a RCTRootView that points to your React Native component and its AppRegistryname that you defined in index.ios.js.
  2. Start the React Native server and run your native application.
  3. Optionally add more React Native components.
  4. Debug.
  5. Prepare for deployment (e.g., via the react-native-xcode.sh script).
  6. Deploy and Profit!

开发环境准备

基础环境

First, follow the Getting Started guide for your development environment and the iOS target platform to install the prerequisites for React Native.

CocoaPods

CocoaPods is a package management tool for iOS and Mac development. We use it to add the actual React Native framework code locally into your current project.

$ sudo gem install cocoapods

It is technically possible not to use CocoaPods, but this requires manual library and linker additions that overly complicates this process.

示例App

Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.

Packag依赖

React Native integration requires both the React and React Native node modules. The React Native Framework will provide the code to allow your application integration to happen.

package.json

We will add the package dependencies to a package.json file. Create this file in the root of your project if it does not exist.

Normally with React Native projects, you will put files like package.json, index.ios.js, etc. in the root directory of your project and then have your iOS specific native code in a subdirectory like ios/ where your Xcode project is located (e.g., .xcodeproj).

Below is an example of what your package.json file should minimally contain.

Version numbers will vary according to your needs. Normally the latest versions for both React and React Native will be sufficient.

{
  "name": "NumberTileGame",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react": "15.0.2",
    "react-native": "0.26.1"
  }
}

React Native框架

The React Native Framework was installed as Node module in your project above. We will now install a CocoaPods Podfilewith the components you want to use from the framework itself.

Subspecs

Before you integrate React Native into your application, you will want to decide what parts of the React Native Framework you would like to integrate. That is where subspecs come in. When you create your Podfile, you are going to specify React Native library dependencies that you will want installed so that your application can use those libraries. Each library will become a subspec in the Podfile.

The list of supported subspecs are in node_modules/react-native/React.podspec. They are generally named by functionality. For example, you will generally always want the Core subspec. That will get you the AppRegistry,StyleSheet, View and other core React Native libraries. If you want to add the React Native Text library (e.g., for <Text>elements), then you will need the RCTText subspec. If you want the Image library (e.g., for <Image> elements), then you will need the RCTImage subspec.

Podfile

After you have used Node to install the React and React Native frameworks into the node_modules directory, and you have decided on what React Native elements you want to integrate, you are ready to create your Podfile so you can install those components for use in your application.

The easiest way to create a Podfile is by using the CocoaPods init command in the native iOS code directory of your project:

## In the directory where your native iOS code is located (e.g., where your `.xcodeproj` file is located)
$ pod init

The Podfile will be created and saved in the iOS directory (e.g., ios/) of your current project and will contain a boilerplate setup that you will tweak for your integration purposes. In the end, Podfile should look something similar to this:

# The target name is most likely the name of your project.
target 'NumberTileGame' do

  # Your 'node_modules' directory is probably in the root of your project,
  # but if not, adjust the `:path` accordingly
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'RCTText',
    'RCTWebSocket', # needed for debugging
    # Add any other subspecs you want to use in your project
  ]

end

Pod安装

After you have created your Podfile, you are ready to install the React Native pod.

$ pod install

Your should see output such as:

Analyzing dependencies
Fetching podspec for `React` from `../node_modules/react-native`
Downloading dependencies
Installing React (0.26.0)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There are 3 dependencies from the Podfile and 1 total pod installed.

代码集成

Now that we have a package foundation, we will actually modify the native application to integrate React Native into the application. For our 2048 app, we will add a “High Score” screen in React Native.

The React Native component

The first bit of code we will write is the actual React Native code for the new “High Score” screen that will be integrated into our application.

Create a index.ios.js file

First, create an empty index.ios.js file. For ease, I am doing this in the root of the project.

index.ios.js is the starting point for React Native applications on iOS. And it is always required. It can be a small file that requires other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will just put everything in index.ios.js

# In root of your project
$ touch index.ios.js

Add Your React Native Code

In your index.ios.js, create your component. In our sample here, we will add simple <Text> component within a styled<View>

'use strict';

import React from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class RNHighScores extends React.Component {
  render() {
    var contents = this.props["scores"].map(
      score => <Text key={score.name}>{score.name}:{score.value}{"\n"}</Text>
    );
    return (
      <View style={styles.container}>
        <Text style={styles.highScoresTitle}>
          2048 High Scores!
        </Text>
        <Text style={styles.scores}>
          {contents}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  highScoresTitle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  scores: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// Module name
AppRegistry.registerComponent('RNHighScores', () => RNHighScores);

RNHighScores is the name of your module that will be used when you add a view to React Native from within your iOS application.

The Magic: RCTRootView

Now that your React Native component is created via index.ios.js, you need to add that component to a new or existingViewController. The easiest path to take is to optionally create an event path to your component and then add that component to an existing ViewController.

We will tie our React Native component with a new native view in the ViewController that will actually host it calledRCTRootView .

Event Handler

We will now add an event handler from the menu link. A method will be added to the main ViewController of your application. This is where RCTRootView comes into play.

When you build a React Native application, you use the React Native packager to create an index.ios.bundle that will be served by the React Native server. Inside index.ios.bundle will be our RNHighScore module. So, we need to point ourRCTRootView to the location of the index.ios.bundle resource (via NSURL) and tie it to the module.

We will, for debugging purposes, log that the event handler was invoked. Then, we will create a string with the location of our React Native code that exists inside the index.ios.bundle. Finally, we will create the main RCTRootView. Notice how we provide RNHighScores as the moduleName that we created above when writing the code for our React Native component.

First import the RCTRootView library.

#import "RCTRootView.h"

The initialProperties are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use this.props to get access to that data.