如何将React Native集成至Android原生应用?
步骤:
在appbuild.gradle的dependencies标签下添加: compile "com.facebook.react:react-native:+";
在appbuild.gradle的android标签下添加: configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:+' }
在appbuild.gradle的androiddefaultConfig标签下添加: ndk { abiFilters "armeabi-v7a", "x86" }
在build.gradle的allprojectsrepositories标签下添加: maven { url "$rootDir/reactnative/node_modules/react-native/android" }
在gradle.properties内添加: android.useDeprecatedNdk=true
创建一个activity文件RNActivity:
public class RNActivity extends ReactActivity {
@Nullable
@Override
protected String getMainComponentName() {
return "demo1031";
}
}
创建一个Application文件RNApplication:
public class RNApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this,false);
}
}
在AndroidManifest.xml内指定application路径android:name=".RNApplication"
在项目目录下创建reactnative文件夹, 在reactnative文件夹创建package.json文件:
{
"name": "reactnative",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.0.0-beta.5",
"react-native": "0.49.5"
},
"devDependencies": {
"babel-jest": "21.2.0",
"babel-preset-react-native": "4.0.0",
"jest": "21.2.1",
"react-test-renderer": "16.0.0-beta.5"
},
"jest": {
"preset": "react-native"
}
}
在reactnative文件夹创建index.android.js文件:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
export default class Index extends Component {
_onPress() {
alert("我是react-native弹窗");
}
render() {
return (
<View style={styles.container}>
<Button title="Button" color="#ff8500" onPress={()=> this._onPress()}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('reactnative', () => Index);
在项目目录文件夹reactnative下执行命令npm i, 然后再npm start
使用Android studio运行项目, ok, 收工!
假如报错: Unable to load script from assets 'index.android.bundle'..., 可以在项目main文件夹下新建文件夹assets, 然后在reactnative下运行命令: react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output ../app/src/main/assets/index.android.bundle --assets-dest ../app/src/main/res/
作者:hello老文
链接:https://www.jianshu.com/p/68940f43e557
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。