React Native 初体验

2017-08-23  本文已影响0人  契约工程师

1. 安装环境,仅以mac为例

1.1 首先安装homebrew(mac系统下的包管理器)

1.2 安装node.js

1.3 安装yarn(代替npm加快node module下载速度)以及react-native-cli(RN的编译打包工具)

1.4 推荐安装watchman, Flow 不推荐!

watchman 能够实时刷新,所见即所得!

1.5 安装Sublime 开发 以及 如何使用package control安装IDE

推荐使用的插件 : ReactJS Emmet Terminal react-native-snippets


2 纯RN语法项目,以项目名称MyApp为例

2.1 创建项目,初始化npm,node.js服务器配置等一系列操作

终端 运行 react-native init MyApp --version 0.44.3

2.2 到MyApp的目录下,直接运行

cd MyApp && react-native run-ios

2.3 简单修改和运行的大致步骤

AppDelegate中修改

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"myAPP" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"module1"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
                                                   

JS文件中修改

AppRegistry.registerComponent('module1', () => clas1);

export default class clas1 extends Component

3 iOS向现有的项目集成RN代码

创建工程,并且将工程纳入pod 管理下,

3.1 在工程的根目录下创建文件夹,随意取名,比如RNComponent

名称,版本和依赖会变化,注意!

{
  "name": "appTest",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.3"
  }
}

内容为要创建的页面的内容,获取原生页面传过来的score,并且显示

'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.highScoresTitle}>
          30000000
        </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,
  },
});

// 整体js模块的名称,注册名称是ssss
AppRegistry.registerComponent('ssss', () => RNHighScores);

3.2 原生工程的集成


  # 'node_modules'目录一般位于根目录中
  # 但是如果你的结构不同,那你就要根据实际路径修改下面的`:path`
  pod 'React', :path => './RNComponent/node_modules/react-native', :subspecs => [
  'Core',
#  'CxxBridge', # 如果RN版本 >= 0.47则加入此行
  'DevSupport', # 如果RN版本 >= 0.43,则需要加入此行才能开启开发者菜单
  'RCTText',
  'RCTNetwork',
  'RCTWebSocket', # 这个模块是用于调试功能的
  # 在这里继续添加你所需要的模块
  
  'ART',
  'RCTActionSheet',
  'RCTAdSupport',
  'RCTGeolocation',
  'RCTImage',
  'RCTPushNotification',
  'RCTSettings',
  'RCTVibration',
  'RCTLinkingIOS',
  ]
  
  # 如果你的RN版本 >= 0.42.0,请加入下面这行
  pod "Yoga", :path => "./RNComponent/node_modules/react-native/ReactCommon/yoga"

pod install

3.3 RN的js代码最终替代的是MVC中的View,所以我们用view来接收RN的代码


func doSome()  {
        
        // 这里如果是要求真机运行,请务必将真机的ip修改到这里来,如果是127.0.0.1或者localhost ,只能模拟器访问 , 平台是ios,开发模式下
        let jsPath = URL(string: "http://172.29.164.9:8081/index.ios.bundle?platform=ios&dev=true")
        
        // 传递的数据,以字典形式传递
        let metaData: Dictionary = ["scores":
            [
                ["name":"william", "value":"42"],
                ["name":"ssss", "value":"10"]
            ]
        ]
        
        // 这里的ssss是js中注册的名称,会找到index.ios.js中的ssss模块
        let rootView = RCTRootView(bundleURL: jsPath, moduleName: "ssss", initialProperties: metaData, launchOptions: nil)
        
        // 设置view
        let vc = UIViewController()
        vc.view = rootView
        self.present(vc, animated: true, completion: nil)
        
}

3.4 启动npm服务,运行项目

npm start

3.5 运行项目即可

找到edit scheme 中的envirment variables ,添加键值对 OS_ACTIVITY_MODE disable

3.6 但是目前有一个问题,一旦远程npm没有启动,就会导致连接失败

如何摆脱node服务器?

react-native bundle --entry-file index.ios.js --platform ios --dev false --bundle-output release_ios/main.jsbundle --assets-dest release_ios/

这里遇到一个BUG,就是swift4.0 如果直接拖到目录,然后拖到工程目录,会导致找不到文件...,只能直接拖到工程目录中!!

还有个问题,如果遇到多个js文件,那怎么批量处理,待续

4 语法分析

4.1 JS 语法

// 从'react'中引入组件
import React, {
  Component,
} from 'react';

// 从react-native 中引入各个单一的组件名称
import {
  TabBarIOS, 
  NavigatorIOS 
} from 'react-native';

//对工程扩展组件
class App extends Component {
  render() {
    return (
      <TabBarIOS>
        <TabBarIOS.Item title="React Native" selected={true}>
          <NavigatorIOS initialRoute={{ title: 'React Native' }} />
        </TabBarIOS.Item>
      </TabBarIOS>
    );
  }
}

几个关键字:export,default,extends关键字

4.2 样式表

var styles = StyleSheet.create({
  row: { flexDirection: 'row', margin: 40 },
  image: { width: 40, height: 40, marginRight: 10 },
  text: { flex: 1, justifyContent: 'center'},
  title: { fontSize: 11, fontWeight: 'bold' },
  subtitle: { fontSize: 10 },
});

这里通过创建一个变量 的样式类 来管理所有的样式

4.3 最重要的,入口文件必须要加,其他文件不必加

// 注意,这里用引号括起来的'HelloWorldApp'必须和你init创建的项目名一致
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);

程序入口文件必须要进行注册,ios才能识别到这个js文件,从这个入口进

5. 技巧

5.1 使用导航控制器以及tab切换控制器

参照 http://www.jianshu.com/p/7d435e199c96

6. 遇到的BUG

前言: 解决BUG说实话还是Stack overflow 靠谱,其他都一般

React Native 真是一堆坑,至少中文网站上一堆坑

6. 使用优缺点介绍

优点 :

缺点 :

总结 : 如果是一线开发人员作为附加技能来说,收益是极高的,但是如果作为主职就会有很多局限性.无论是RN还是swift 或者kotlin,未来的方向是增加通用性,swift 开发服务器,swift 开发Android也有人在研究,swift web开发也已经提出.

其他人出现的错误集锦1,感谢作者

其他人出现的错误集锦2,感谢作者

最后的总结部分,对于刚接触的人很友好

官方文档

上一篇 下一篇

猜你喜欢

热点阅读