如何在 React 中使用 i18n-iso-countries?

jup*_*lly 4 javascript node.js npm reactjs

我正在开发一个 React 应用程序并尝试使用 i18n-iso-countries 包来获取一个英文国家对象,该对象的键为 iso 代码,值为国家/地区名称。这在 node 中很容易,因为我已经使用一个简单的脚本进行了验证,该脚本运行 i18n-iso-countries npm 文档显示的方式,如下所示:

const countries = require("i18n-iso-countries");
console.log(countries.getNames('en'));
Run Code Online (Sandbox Code Playgroud)

但是当我在我的反应应用程序(用 create-react-app 制作)中这样做时......

import countries from "i18n-iso-countries";
console.log(countries.getNames('en'));
Run Code Online (Sandbox Code Playgroud)

...我得到一个空物体。当我在 React 中只记录国家 (console.log(countries)) 时,我看到函数“getNames”和文档提到的其他函数,所以我不确定是什么给出的。

jup*_*lly 6

只需要添加这一行!

countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
Run Code Online (Sandbox Code Playgroud)

不知道为什么需要在 React(和 Angular - 我在那里找到答案如何在 Angular 6 中使用 i18n-iso-countries - 以及其他 ui 库/框架)中添加它,所以如果有人能解释一下,那会很酷,但是,嘿,至少它起作用了!