由於這是關於數據的一切,您不需要特殊的React庫。您只能使用有關像here這樣的國家/地區的數據。這是在下面的模式JSON(我削減了一些領域,完整的例子可以發現here):
{
"name": {
"common": "Austria",
"official": "Republic of Austria",
"native": {
"bar": {
"official": "Republik Österreich",
"common": "Österreich"
}
}
},
"cca2": "AT",
"cca3": "AUT",
"translations": {
"deu": {"official": "Republik Österreich", "common": "Österreich"},
"fra": {"official": "République d'Autriche", "common": "Autriche"},
"ita": {"official": "Repubblica d'Austria", "common": "Austria"},
"jpn": {"official": "オーストリア共和國", "common": "オーストリア"},
"spa": {"official": "República de Austria", "common": "Austria"}
},
}
注意,雖然翻譯部分採用ISO 639-3
碼和識別部分使用ISO 3166-1
代碼,你可以很容易地將它們映射因爲土生土長的語言部分使用ISO 639-3
代碼。
假設您必須顯示預定義的國家列表。你所要做的就是獲得他們的cca3
代碼並將它們放入一個數組中。然後,當你在ISO 639-3
格式(userLoc在下面的例子中)發現你的用戶區域,可以使用lodash或類似的庫來獲得相應的翻譯:
// userLoc - current user locale in ISO 639-3
// codesToSelect - array of country codes in ISO 3166-1 you want to show
_.map(codesToSelect, (cca3) => {
let countryObject = _.find(countriesData, { 'cca3': cca3 });
let translatedName = (countryObject &&
countryObject.translations &&
countryObject.translations[ userLoc ])
? countryObject.translations[ userLoc ]
: cca3
return translatedName;
})
注意,有可能不是一個指定的翻譯國家代碼,所以cca3將被用作後備。