- 打開
cmd
,進入工程目錄
npm init //提醒生成package.json文件
這個命令提示需要輸入部分信息,如圖
命令行
生成文件如下:
package.json
當然,文件內(nèi)容我們后續(xù)還可以使用編輯器修改。
- 安裝
React
和React Native
npm install --save react react-native //安裝React 和React Native
- 下載
.flowconfig
文件
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig //下載.flowconfig文件
也可以手動創(chuàng)建.flowconfig文件辉阶,點擊這里復(fù)制文本內(nèi)容到文件中
- 在
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"
}
}
...
}
添加權(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
中啟動服務(wù)
npm start
//等效`package.json`中的`node node_modules/react-native/local-cli/cli.js start`
運行 `npm start`睛藻,看到下圖表示啟動成功
image.png
- 運行模擬器,啟動定義的MyReactActivity即可
參考鏈接:
史上最詳細的Android原生APP中添加ReactNative 進行混合開發(fā)教程
原生 Android 項目集成 React Native