react native

返回
Author Avatar
钢翼
2021-11-22
编程
74

1.根据上一篇文章配置好idea的Android环境

2.新建react native项目

# 下面的demo为你的项目名称
npx react-native init demo

3.开启AVD模拟器

可以在idea中开启

4.启动程序

cd demo
npm run android

第一次会执行Bundling,等待时间会比较长。

5.用idea社区版启动程序

先启动AVD模拟器。
用idea打开项目下的android目录。

可能会报以下错误

This version of the Android Support plugin for IntelliJ IDEA (or Android Studio) cannot open this project, please retry with version 4.2 or newer.

打开项目下的android\buid.gradle,找到下面代码

classpath("com.android.tools.build:gradle:4.2.2")

将其改成

classpath("com.android.tools.build:gradle:4.1.1")

然后重新加载gradle并运行又会报以下错误

> Task :app:compileDebugJavaWithJavac FAILED
E:\Git\rn-demo\demo1\android\app\src\debug\java\com\demo1\ReactNativeFlipper.java:43: ����: ���ڲ����з��ʱ��ر���networkFlipperPlugin; ��Ҫ������Ϊ��������
              builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

原因是ReactNativeFlipper这个类在lambda里面使用的外部变量没有用final。 这里打开该文件,在对应变量声明中添加final修饰语即可。

如果项目没有执行过react-native start,会报以下错误

Unable to load script.Make sure you're either running a metro server(run 'react-native start' ) or thatyour bundle 'index.android.bundle' is packaged correctly for release

可以在android\app\buid.gradle文件中找到以下代码

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
]

在后面添加以下代码,使其能在debug模式下执行bundling

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
    bundleAssetName:"index.android.bundle",
    bundleInDebug:true,
    bundleInAlpha:true,
    bundleInBeta:true
]