Android在原生集成react native

react native使用方式有两种:
1:直接新建一个react native项目
2:在已经存在的原生项目中集成react native项目。
今天主要讲解第二种方式的步骤。
1:新建Android原生项目
2:在原生项目的根目录下执行npm init 输入package名字我是用的Android项目的名字这里是testApp,其他配置会直接写入到package.json中
3:npm install –save react react-native
安装node_modules包
4:打开package.json 将

"start": "node node_modules/react-native/local-cli/cli.js start"

加入到scripts里面
如下:

{
  "name": "testapp",
  "version": "1.0.0",
  "description": "test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.2.0",
    "react-native": "^0.50.4"
  }
}

5:在根目录下新建index.js
如下:

export default class App extends Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.hello}>Hello, My Hybrid App!</Text>
            </View>
        )
    }
}
AppRegistry.registerComponent('testApp', () => App);

文件目录结构:
9F867E6B-5703-4EF5-946A-65D52C6EF0CC.png

6:在app/build.gradle中配置

 compile "com.facebook.react:react-native:+" // From node_modules.

7:android新建MyReactActivity集成AppCompatActivity实现DefaultHardwareBackBtnHandler。
其中onCreate方法中

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.bundle")
                .setJSMainModulePath("index")//0.5以后使用这个方法 因为版本发生变化setJSMainModuleName("index.android")这个方法没有了
/**另外有些人这里配置index.android其实配置index.android或者index都可以 主要是要保持这里配置的名字和步骤5中新建的文件名字一致即可**/
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        // 注意这里的HelloWorld必须对应“index.js”中的
        // “AppRegistry.registerComponent()”的第一个参数
      mReactRootView.startReactApplication(mReactInstanceManager, "testApp", null);
        setContentView(mReactRootView);
    }

8:manifest.xml里面配置

<uses-permission android:name="android.permission.INTERNET" />
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name=".MyReactActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        </activity>

9:运行现在根目录下启动node
运行npm start
然后android studio运行。如图:
andoridtoRN.gif
完成代码GitHub:https://github.com/wuyunqiang/AndroidToRN
仅供参考。
如要运行需要下载node_modules.

猜你喜欢

转载自blog.csdn.net/u014041033/article/details/78686567