美文网首页Android技术知识
集成ReactNative到Native App中

集成ReactNative到Native App中

作者: 小编 | 来源:发表于2016-10-21 17:55 被阅读69次
  1. 打开cmd,进入工程目录
npm init   //提醒生成package.json文件

这个命令提示需要输入部分信息,如图

命令行

生成文件如下:


package.json

当然,文件内容我们后续还可以使用编辑器修改。

  • 安装ReactReact Native
npm install --save react react-native  //安装React 和React Native
  • 下载.flowconfig文件
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig //下载.flowconfig文件

也可以手动创建.flowconfig文件,点击这里复制文本内容到文件中

  • package.json文件里scripts标签下添加start配置
"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  • 添加index.android.js到项目中
'use strict';
import React from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
class HelloWorld extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.hello}>Hello, World</Text>
      </View>
    )
  }
}
var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  hello: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
  • app模块下 build.gradle配置
dependencies {
...
compile "com.facebook.react:react-native:+" // From node_modules.
}

注意: 最新版本中支持的是23,appcompat-v7:23.0.1**,暂时没有试24的api

  • 整个工程下build.gradle配置
allprojects {
repositories {
    ...
    maven {
        // All of React Native (JS, Android binaries) is installed from npm
        url "$rootDir/node_modules/react-native/android"
    }
}
...
}
  • 添加权限
    AndroidManifest.xml添加<uses-permission android:name="android.permission.INTERNET" />

  • 集成ReactActivity

public class MyReactActivity extends ReactActivity {
    @Nullable
    @Override
    protected String getMainComponentName() {
        return "HelloWorld";//组件名
    }
}
  • Terminal中启动服务
npm start 
//等效`package.json`中的`node node_modules/react-native/local-cli/cli.js start`
运行 `npm start`,看到下图表示启动成功
image.png
  • 运行模拟器,启动定义的MyReactActivity即可

参考链接:
史上最详细的Android原生APP中添加ReactNative 进行混合开发教程
原生 Android 项目集成 React Native

相关文章

网友评论

    本文标题:集成ReactNative到Native App中

    本文链接:https://www.haomeiwen.com/subject/lfqcuttx.html