简体   繁体   English

如何配置 react-intl 以使所有方言区域都回退到其母语?

[英]How do I configure react-intl to have all dialect locales fall back to their parent language?

I've built a site that translates nicely between en and zh locales, using a select element.我已经使用 select 元素构建了一个可以很好地在enzh语言环境之间转换的站点。 Now, I'd like to have my code choose the initial locale based on the value of navigator.language .现在,我想让我的代码根据navigator.language的值选择初始语言环境。 This led to my realization that my locale is en-US , not en .这让我意识到我的语言环境是en-US ,而不是en When I applied that value to the locale property of <IntlProvider /> , a lot of new errors were thrown.当我将该值应用于<IntlProvider />的 locale 属性时,抛出了许多新错误。

Error: [React Intl Error MISSING_TRANSLATION] Missing message: "details.reference" for locale "en-US", using default message as fallback.

The UI still looked fine, since the default messages were in English. UI 看起来仍然很好,因为默认消息是英文的。 And I'm guessing that these errors are silenced in production.而且我猜这些错误在生产中被消除了。

But, the same issue occurs in Chinese.但是,同样的问题出现在中文中。 If a user has their OS/browser locale set to zh-HK , react-intl displays the default messages (in English) instead of the translations in zh.json .如果用户的操作系统/浏览器区域设置为zh-HK ,react-intl 会显示默认消息(英文)而不是zh.json中的翻译。

Is there a clever way to fix this?有没有聪明的方法来解决这个问题? I know that I could clip the geography part of a locale off before passing it to <IntlProvider /> , but that seems hackier than necessary...我知道我可以在将语言环境的地理部分传递给<IntlProvider />之前将其剪掉,但这似乎比必要的更骇人听闻......

I wrote a function to get around the problem for now, but hoping to find a better solution.我写了一个 function 来解决这个问题,但希望能找到更好的解决方案。

const [locale, setLocale] = React.useState(getBrowserLocale());

...

<IntlProvider locale={locale} messages={messages[locale]}>

// @see https://tools.ietf.org/rfc/bcp/bcp47.txt

function getBrowserLocale() {
  switch (navigator.language) {
    case "zh":
    case "zh-Hant":
    case "zh-Hans":
    case "zh-TW":
    case "zh-HK":
    case "zh-CN":
      return "zh";
    // case "zh-CN":
    //   return "zh-CN";
    default:
      return "en";
  }
}

export default getBrowserLocale;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM