集成ReactNative到Native App中

  1. 打開(kāi)cmd,進(jìn)入工程目錄
npm init   //提醒生成package.json文件

這個(gè)命令提示需要輸入部分信息,如圖

命令行

生成文件如下:


package.json

當(dāng)然,文件內(nèi)容我們后續(xù)還可以使用編輯器修改。

  • 安裝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文件

也可以手動(dòng)創(chuàng)建.flowconfig文件,點(diǎn)擊這里復(fù)制文本內(nèi)容到文件中

  • package.json文件里scripts標(biāo)簽下添加start配置
"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  • 添加index.android.js到項(xiàng)目中
'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**,暫時(shí)沒(méi)有試24的api

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

  • 集成ReactActivity

public class MyReactActivity extends ReactActivity {
    @Nullable
    @Override
    protected String getMainComponentName() {
        return "HelloWorld";//組件名
    }
}
  • Terminal中啟動(dòng)服務(wù)
npm start 
//等效`package.json`中的`node node_modules/react-native/local-cli/cli.js start`
運(yùn)行 `npm start`,看到下圖表示啟動(dòng)成功
image.png
  • 運(yùn)行模擬器,啟動(dòng)定義的MyReactActivity即可

參考鏈接:
史上最詳細(xì)的Android原生APP中添加ReactNative 進(jìn)行混合開(kāi)發(fā)教程
原生 Android 項(xiàng)目集成 React Native

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容