最近自己也是刚在学习React Native的知识,在学习到React Native 嵌入到原生应用的时候,感觉遇到了各种坑,这里做一下记录。若有说得不对的地方,谢谢大家纠正。
React Native嵌入到原生应用的教程在其官方指导文档里也有,但是感觉很多注意点没讲到,现在,我们就一步步来,我们这里的前提是开发环境已经搭配好。
第一步,在 Android Studio 上新建一个工程,这一步没什么好说的,然后在main目录下面创建一个assets 的文件夹。
第二步,打开下面的终端 Terminal,分别执行以下三条语句:
npm init
npm install --save react react-native
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
先输入 npm init ,然后会出现下面的情况,划红线的都是需要自己输入的,看着我的随便写点就行
执行第二条命令
npm install --save react react-native
,执行完之后你会发觉多了一个叫node_modules的文件夹,接着执行第三条命令
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
执行完,第三条命令之后又会生成一个.flowconfig的文件
第三步,将
"start": "node node_modules/react-native/local-cli/cli.js start"
这条语句copy到 data.json中的scripts中,如下图
第四步,项目根目录中创建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);
第五步,给工程添加React Native依赖包,如果你想下载一个随意版本的依赖包【建议下载最新版本的React Native依赖包】,就在你APP module下面的build.gradile文件中 的 dependencies中添加 compile "com.facebook.react:react-native:+" // From node_modules.
dependencies {
...
compile "com.facebook.react:react-native:+" // From node_modules.
}
如果你不想下载一个随意的版本的React Native依赖包,你可以指定下你要下载的React Native依赖包的版本