在Android React Native应用程序中正确使用Intl

问题描述 投票:0回答:6

我正在尝试使用

Intl
的数字格式化程序,它在 iOS 上完美运行,并且当调试器附加到 iOS 或 Android 时,但由于 Android 中的 JSC 过时,仅在没有附加调试器的 Android 上失败。

经过一番研究,我发现了两种可能的解决方案:

  • 使用
    Intl
    polyfill
  • 在Android中使用自定义JSC

在使用纱线安装

Intl
intl
之后,我首先尝试了
react-intl
polyfill:

//in my app's index.js
if (!global.Intl) {
    global.Intl = require('intl');
}

虽然它仍然说

ReferenceError: Can't find variable: Intl

然后我放弃并尝试包含自定义 JSC(我已经确认自定义 AAR 被正确引用),但我仍然遇到相同的错误。无论我做什么,如果没有附加调试器,我都无法在 Android 上运行

Intl

我做错了什么? (我使用的是 React Native 0.59.9)

android react-native polyfills javascriptcore react-intl
6个回答
49
投票

小更新,从 React Native v0.60+ 开始,您可以定义 lib+ 版本。

在你的

app/build.gradle

def jscFlavor = 'org.webkit:android-jsc-intl:+'

并在下面的依赖项中实现它:

dependencies {
    ...
    if (enableHermes) {
        ...
    } else {
        implementation jscFlavor
    }
}

20
投票

如果您的 app/build.gradle 中没有禁用 Hermes 的选项,并且您无法使用

org.webkit:android-jsc-intl:+
,那么 Intl polyfill 可以解决该问题:

npm install intl

代码中:

import 'intl';
import 'intl/locale-data/jsonp/en'; // or any other locale you need

11
投票
npm i intl

导入后

import "intl";

import "intl/locale-data/jsonp/en";

然后使用

Intl

例如

new Intl.NumberFormat(
  "en-IN",
  {
    style: "currency",
    currency: "INR",
  })
  .format(
     (travelTimeInformation?.duration.value *
      SURGE_CHARGE_RATE *
      multiplier) /
      100
    )}

3
投票

如果您使用的是 React Native v0.60+

app/build.gradle
如果您已经有
jscFlavor

喜欢,

def jscFlavor = 'org.webkit:android-jsc:+'

替换为,

def jscFlavor = 'org.webkit:android-jsc-intl:+'

并在依赖项中实现

dependencies {
  if (enableHermes) {
    ...
  } else {
    implementation jscFlavor
  }
}

1
投票

如果您使用自定义 JSC,请不要忘记导入国际版本,如 JSC Android Buildscripts 的自述文件中所述

对于 React Native 0.59 版本,将原始工件 id 替换为 android-jsc-intl

dependencies {
+   // Make sure to put android-jsc at the the first
+   implementation "org.webkit:android-jsc-intl:r241213"
+
    compile fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

0
投票

我想删除这个问题,但我不能,因为已经有另一个答案了。


与JSC无关。我的构建脚本没有正确更新 APK,而我认为是这样,而且我一遍又一遍地尝试旧的伪造 APK。否则,显然我做的一切都正确,因为它现在可以与新的 APK 一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.