简体   繁体   English

页面的多种语言(react-i18next)

[英]Multiple languages for page (react-i18next)

I am using react-i18next lib for languages.我正在为语言使用 react-i18next 库。

Problem : I need to use user language for website but for article i need to use language of this article.问题:我需要为网站使用用户语言,但对于文章我需要使用本文的语言。

My solution : I want to wrap current article in another I18nextProvider and pass article lang to it.我的解决方案:我想将当前文章包装在另一个 I18nextProvider 中并将文章 lang 传递给它。 I hope it will be fine:) If it's works i will write solution here.我希望它会很好:) 如果它有效,我会在这里写解决方案。

My question : Maybe exists another solution of this problem?我的问题:也许存在这个问题的另一种解决方案?

It's works:其作品:

export const LanguageContainer: React.FC<Props> = (props) => {
  const i18n = React.useMemo(() => {
    const xhr = new XHR(undefined, {
      loadPath: (languages, namespace) => {
        const version = app.Version ? `?v=${app.Version}` : '';
        const dir = app.Production ? Configuration.Localization.RootDir : Configuration.Localization.DefaultRootDir;
        return url.resolve(dir, `./${props.lang}/${namespace}.json${version}`);
      },
    });
    const I18n = i18next.createInstance().use(xhr);

    I18n.init({
      ns: ['general'],
      defaultNS: 'general',
      fallbackLng: Configuration.Localization.DefaultLanguage,
      whitelist: Configuration.Localization.Languages.map((x) => x.key),
    });

    return I18n;
  }, [props.lang]);

  return (
    <I18nextProvider i18n={i18n}>
      {props.children}
    </I18nextProvider>
  );
};

And how to use:以及如何使用:

<LanguageContainer lang="en">
   // here components which need to use lang en     
</LanguageContainer>
<LanguageContainer lang=({language})>
  // here components which need to use lang en     
</LanguageContainer>

This is the best away, because this value is object who you send from customers components.这是最好的,因为这个值是 object 您从客户那里发送的组件。 And not bad idea in this case use context在这种情况下使用上下文也不错

A simpler solution to get additional languages is to call i18n.getFixedT('language-code') .获取其他语言的更简单的解决方案是调用i18n.getFixedT('language-code')

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

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