FinClip为企业提供小程序生态圈技术产品,开发者可在FinClip小程序开发帮助中心找到相关FinClip小程序指引

# React Native 常见问题

# 1. 可以使用其他 react-native 版本的 demo 吗?

答:因为 react-native 不同版本的差别较大,建议使用 0.67.4 的 react-native 版本去运行我们的官方 demo.

# 2. 如何清理项目缓存?

答:清理缓存可使用 Metro 的清理工具 (opens new window).

# 3. iOS 端在 M1 运行不了 pod install?

答:使用 arch -x86_64 pod install替代 pod install.

# 4. 运行 demo 时出现:No matching variant of com.facebook.react:react-native:0.71.0-rc.0 was found 报错

答: 参考 #issue-35210 (opens new window) 解决

# 5. 用 Android Studio 运行 react-native demo 时,出现:Cannot run program "node": error=2, No such file or directory 报错

答:在终端通过输入命令: open -a /Applications/Android\ Studio.app 的方式打开

# 6. 如遇: Plugin with id maven not found. 报错

答:请把 react-native-mopsdk 升级至 2.0.1 版本

# 7. 如何要升级react-native版本到比较高的版本(如:0.73.0)?

答:

  1. 使用RN官方升级版本对比工具查看要更新的所有文件(比如从0.67.4升级至0.73.0):https://react-native-community.github.io/upgrade-helper/?from=0.67.4&to=0.73.0

  2. 准备好环境:更新最新版本的 Android Studio(版本过低无法编译)、 安装好较新版本的JDK(JDK17-JDK20)、更新node版本(node 18以上,最好用20)、安装好yarn(据说使用npm安装依赖包等,有时候会报错)。

  3. 按照步骤1,修改android 工程和iOS 工程。

以下是我们升级过程中修改的文件:

android部分

首先,gradle版本修改:文件路径gradle/wrapper/gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

然后,修改app目录下的build.gradle(app/build.gradle)

这里要注意以前的一些库被删掉了;所以可能会出现“ReactNativeFlipper”这个类被引用的地方报错,直接删除项目里面这个类就好。新增的库里面直接就有这个类无需在项目里面自定义了,直接导包即可。 另外,manifest文件里面的package属性要删除掉。

apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    // reactNativeDir = file("../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
    // codegenDir = file("../node_modules/@react-native/codegen")
    //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
    // cliFile = file("../node_modules/react-native/cli.js")

    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]

    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]
    //
    //   The command to run when bundling. By default is 'bundle'
    // bundleCommand = "ram-bundle"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []

    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]
}

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdk  rootProject.ext.compileSdkVersion

    namespace "com.finogeeks.finclip.demo"

    defaultConfig {
        applicationId "com.finogeeks.finclip.demo"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")
    implementation("com.facebook.react:flipper-integration")

    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)


      

然后,修改根目录下的build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.


buildscript {
    ext {
        buildToolsVersion = "33.0.1"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33

        // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
        ndkVersion = "23.1.7779620"
    }
    repositories {
        google()
        jcenter()

        google()
        jcenter()
        maven {
            url "https://gradle.finogeeks.club/repository/applet/"
            credentials {
                username "applet"
                password "123321"
            }
        }
        maven { url "https://jitpack.io" }
    }
    dependencies {
        classpath('com.android.tools.build:gradle:8.3.0')
        classpath("com.facebook.react:react-native-gradle-plugin")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven {
            url "https://gradle.finogeeks.club/repository/applet/"
            credentials {
                username "applet"
                password "123321"
            }
        }
        maven { url "https://jitpack.io" }
    }
}


iOS部分 首先,修改podfile文件(使用提示的版本替换内容)。

# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
  'require.resolve(
    "react-native/scripts/react_native_pods.rb",
    {paths: [process.argv[1]]},
  )', __dir__]).strip

platform :ios, min_ios_version_supported
prepare_react_native_project!

# If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
# because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
#
# To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
# ```js
# module.exports = {
#   dependencies: {
#     ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
# ```
flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled

linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
  Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
  use_frameworks! :linkage => linkage.to_sym
end

target 'example' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # Enables Flipper.
    #
    # Note that if you have use_frameworks! enabled, Flipper will not work and
    # you should disable the next line.
    :flipper_configuration => flipper_config,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'exampleTests' do
    inherit! :complete
    # Pods for testing
  end

  post_install do |installer|
    # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
    react_native_post_install(
      installer,
      config[:reactNativePath],
      :mac_catalyst_enabled => false
    )
  end
end

然后,修改AppDelegate中的内容。

如果遇到FlipperTransportTypes.h'报错,可以在podfile中添加这一段(因为头文件中少加了#include <functional>)。

installer.pods_project.targets.each do |target|
  if target.name == 'Flipper'
    file_path = 'Pods/Flipper/xplat/Flipper/FlipperTransportTypes.h'
    contents = File.read(file_path)
    unless contents.include?('#include <functional>')
      File.open(file_path, 'w') do |file|
        file.puts('#include <functional>')
        file.puts(contents)
      end
    end
  end
end

# 8. 如何自定义loading页面?

  1. 在iOS 工程内创建一个集成自FATBaseLoadingView的子类。
@interface LoadingView : FATBaseLoadingView
@end


@implementation LoadingView
- (instancetype)initWithFrame:(CGRect)frame {
    if ([super initWithFrame:frame]) {
        
        // 在这里调整视图的属性
        self.loadingView.dotView.backgroundColor = [UIColor blackColor];
        self.loadingView.animation.duration = 5;
        self.titleLabel.textColor = [UIColor redColor];
    }
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 在这里调整视图的布局等。
    // 如果要改logo,必须在这里修改。
    // 注意:修改小程序logo应该是从管理后台上传新的小程序图标,因为更多面板、关于页面也会展示小程序logo,只改这里只是loding页面生效
    self.loadingView.iconImageView.image = [UIImage imageNamed:@"mini_logo"];
}
@end
  1. 在Android 工程内创建自定义的loading视图,继承自IFinAppletLoadingPage。
class CustomLoadingPage constructor(context: Context) : IFinAppletLoadingPage(context) {
 
    override fun getFailureLayoutRes(): Int {
        // 错误页布局资源文件
        return R.layout.loading_failure_layout
    }
 
    override fun getLoadingLayoutRes(): Int {
        // 加载页布局资源文件
        return R.layout.loading_layout
    }
 
    override fun onLoadingFailure(msg: String) {
        // 该方法已废弃,留空即可,请使用下面的 onLoadingFailure(title: String, msg: String)
    }
 
    override fun onLoadingFailure(title: String, msg: String) {
        // 错误页错误消息正文
        failureLayout.findViewById<TextView>(R.id.tvLoadingFailedTitle).text = title
        failureLayout.findViewById<TextView>(R.id.tvLoadingFailedMsg).text = msg
    }
 
    override fun onUpdate(appTitle: String, appAvatarUrl: String) {
        // 加载页小程序名字
        loadingLayout.findViewById<TextView>(R.id.tvTitle).text = appTitle
        // 加载页小程序图标
        ImageLoader.get(context).load(appAvatarUrl, object : DrawableCallback {
            override fun onLoadFailure() {
 
            }
 
            override fun onLoadSuccess(r: Drawable) {
                val ivAvatar = loadingLayout.findViewById<RoundedImageView>(R.id.ivAvatar)
                // 不要直接使用Handler post设置图标,应该先判断是否主线程,如果是主线程则直接设置图标,
                // 避免主线程更新时因Handler post导致图标显示时机变慢。
                if (Looper.myLooper() == Looper.getMainLooper()) {
                    ivAvatar.setImageDrawable(r)
                } else {
                    handler.post {
                        ivAvatar.setImageDrawable(r)
                    }
                }
            }
        })
    }
}
  1. 实现android 对应的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/fin_color_bg_pure_auto"
    android:orientation="vertical">
 
    <RelativeLayout
        android:id="@+id/rlLoading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">
 
        <FrameLayout
            android:id="@+id/flAvatar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true">
 
            <com.finogeeks.lib.applet.modules.appletloadinglayout.FinAppletLoadingSurfaceView
                android:id="@+id/finAppletLoadingView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center" />
 
            <com.finogeeks.lib.applet.externallib.makeramen.roundedimageview.RoundedImageView
                android:id="@+id/ivAvatar"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:layout_gravity="center"
                android:src="@color/color_ebeced"
                app:fin_applet_riv_corner_radius="6dp" />
        </FrameLayout>
 
        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/flAvatar"
            android:layout_centerHorizontal="true"
            android:ellipsize="end"
            android:gravity="center"
            android:maxLines="2"
            android:textAlignment="center"
            android:textColor="@color/fin_color_text_auto"
            android:textSize="18sp"
            android:textStyle="bold" />
    </RelativeLayout>
 
    <ImageView
        android:id="@+id/ivTechSupport"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="45dp"
        android:src="@drawable/fin_applet_tech_support"
        android:visibility="gone"
        tools:visibility="visible" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/fin_color_bg_pure_auto"
        android:orientation="vertical">
 
 
  <TextView
          android:id="@+id/tvAppName"
          android:layout_width="wrap_content"
          android:layout_height="@dimen/fin_applet_navbar_height"
          android:layout_alignParentTop="@+id/rlLoadingFailed"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="30dp"
          android:gravity="center"
          android:textColor="@color/fin_color_text_auto"
          android:textSize="18sp"
          android:textStyle="bold"
          android:visibility="gone"
          tools:text="小程序名称"
          tools:visibility="visible" />
 
  <RelativeLayout
          android:id="@+id/rlLoadingFailed"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:layout_marginTop="125dp">
 
    <ImageView
            android:id="@+id/ivLoadingFailed"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_centerHorizontal="true"
            android:src="@drawable/fin_applet_loading_error"
            tools:ignore="ContentDescription" />
 
    <TextView
            android:id="@+id/tvLoadingFailedTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ivLoadingFailed"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="25dp"
            android:gravity="center"
            android:text="@string/fin_applet_loading_failed_tip_without_message"
            android:textColor="@color/fin_color_text_auto"
            android:textSize="18sp"
            android:textStyle="bold" />
 
    <TextView
            android:id="@+id/tvLoadingFailed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tvLoadingFailedTitle"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:textColor="@color/fin_color_secondary_text_auto"
            android:textSize="15sp"
            tools:text="错误提示" />
  </RelativeLayout>
 
  <!--  注意 fin_btn_fail_reload_margin_bottom 横竖屏的时候距离会不一样。 -->
  <TextView
          android:id="@+id/btnFailReload"
          android:layout_width="wrap_content"
          android:layout_height="40dp"
          android:layout_alignParentBottom="true"
          android:layout_centerHorizontal="true"
          android:layout_marginBottom="@dimen/fin_btn_fail_reload_margin_bottom"
          android:background="@drawable/fin_applet_btn_reload_blue"
          android:gravity="center"
          android:minWidth="200dp"
          android:text="@string/fin_applet_load_again"
          android:textColor="@android:color/white"
          android:textSize="15sp" />
 
</RelativeLayout>
  1. 初始化SDK时,设置安卓和iOS的自定义loading视图类
// iOS 是设置baseLoadingViewClass; android 是设置loadingLayoutCls
let config = new Config(finStoreConfigs, {
  language:LanguageType.Chinese,
  userId:"123456789",
  debug:true,
  appletDebugMode:BOOLState.BOOLStateTrue,
  baseLoadingViewClass:"LoadingView"
}) ;
let uiConfig = new UIConfig({
  isHideClearCacheMenu:true,
  loadingLayoutCls:"com.example.MyAppletLoadingPage"
});
© FinClip with ❤ , Since 2017