使用i18next-browser-languagedetector检测浏览器的语言以实现reactJs Web应用

时间:2018-08-16 18:49:19

标签: reactjs i18next

我有一个reactJs应用程序,我想为其添加本地化。我以前从未使用过i18next,但我正在努力适应它。我的问题是,我无法检测到用户浏览器的使用语言。这是我的代码,能否请您提供一些代码,我已经搜索了该主题的所有文档和答案,但找不到任何解决方案。

这是我的i18n.js文件,正在将其导入我要使用的文件中

<div>

在这些文件中,我这样使用

import i18next from 'i18next';
import languageDetector from 'i18next-browser-languagedetector';
i18next
    .use(languageDetector)
    .init({
        debug: true,
        fallbackLng: "en",
        resources: {
            en: {
                translation: {
                    "table": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "rejected": "Rejected"
                    },

                    "auth": {
                        "signIn": "Sign In",
                        "signOut": "Sign Out",
                        "joinUs": "Join Us",
                        "goBack": "Go Back",
                        "email": "E-mail",
                        "username": "Username",
                        "password": "Password",
                    },

                    "admin": {
                        "employee": "Employees",
                        "moderator": "Moderator",
                        "admin": "Admin",
                        "refreshCounters": "Refresh Counters",
                        "refreshCounter": "Refresh Counter",
                        "setAsEmployee": "Set as Employee",
                        "setAsAdmin": "Set as Admin",
                        "setAsModerator": "Set as Moderator",
                        "email": "E-mail",
                        "password": "Password",
                        "answeredFortunes": "Answered Fortunes",
                        "controlledFortunes": "Controlled Fortunes",
                    },

                    "moderator": {
                        "approve": "Approve",
                        "reject": "Reject",
                        "topic": "Topic",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "gender": "Gender",
                        "answer": "Answer"
                    },

                    "answer": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "send": "Send",
                        "rejectionReason": "Rejection Reason",
                        "rejection": "Rejection",
                        "rejectedAnswer": "Rejected Answer",
                        "unassign": "Unassign"
                    },

                    "modal": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "assignToMe": "Assign to Me",
                        "cancel": "Cancel"
                    },

                    "profile": {
                        "name": "Name",
                        "age": "Age",
                        "email": "E-mail",
                        "answeredFortunes": "Answered Fortunes",
                        "controlledFortunes": "Controlled Fortunes",
                        "employeeTypeAdmin": "Admin",
                        "employeeTypeModerator": "Moderator",
                        "employeeTypeEmployee": "Employee",
                    },

                    "errors": {},
                }
            },
            tr: {
                translation: {
                    "table": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Cinsiyet",
                        "rejected": "Reddedildi"
                    },

                    "auth": {
                        "signIn": "Giriş Yap",
                        "signOut": "Çıkış Yap",
                        "joinUs": "Bize Katıl",
                        "goBack": "Geri Dön",
                        "email": "E-mail",
                        "username": "Kullanıcı Adı",
                        "password": "Şifre",
                    },

                    "admin": {
                        "employee": "Yorumcu",
                        "moderator": "Moderatör",
                        "admin": "Admin",
                        "refreshCounters": "Sayaçları Sıfırla",
                        "refreshCounter": "Sayacı Sıfırla",
                        "setAsEmployee": "Yorumcu Yap",
                        "setAsAdmin": "Admin Yap",
                        "setAsModerator": "Moderatör Yap",
                        "email": "E-mail",
                        "password": "Şifre",
                        "answeredFortunes": "Gönderilen Fallar",
                        "controlledFortunes": "Kontrol Edilen Fallar",
                    },

                    "moderator": {
                        "approve": "Onayla",
                        "reject": "Reddet",
                        "topic": "Konu",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "gender": "Cinsiyet",
                        "answer": "Fal Gönderi"
                    },

                    "answer": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Cinsiyet",
                        "send": "Gönder",
                        "rejectionReason": "Reddedilme Nedeni",
                        "rejection": "Reddedilme",
                        "rejectedAnswer": "Reddedilen Gönder",
                        "unassign": "Fal'ı Bırak"
                    },

                    "modal": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Yaş",
                        "assignToMe": "Bana Ata",
                        "cancel": "İptal"
                    },

                    "profile": {
                        "name": "Ad",
                        "age": "Yaş",
                        "email": "E-mail",
                        "answeredFortunes": "Gönderilen Fallar",
                        "controlledFortunes": "Kontrol Edilen Fallar",
                        "employeeTypeAdmin": "Admin",
                        "employeeTypeModerator": "Moderatör",
                        "employeeTypeEmployee": "Yorumcu",
                    },

                    "errors": {},
                }
            }
        }
    });

export default i18next;

这在网页上显示“问题”,但如果我将Google chrome浏览器更改为土耳其语,则仍为英语。我不知道我在想什么。

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

这对我有帮助。

(感谢:https://velog.io/@hyounglee/TIL-80

 import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import XHR from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";

import translationEn from "../src/lang/translation.en.json";
import translationKo from "../src/lang/translation.ko.json";

const languages = ["en", "ko"]; // (*)

const resource = {
  en: {
    translation: translationEn,
  },
  ko: {
    translation: translationKo,
  },
};

i18n
  .use(XHR)
  .use(initReactI18next)
  .use(LanguageDetector)
  .init({
    // detection: options,
    detection: { order: ["path", "navigator"] },
    fallbackLng: "en",
    resources: resource,
    whitelist: languages,
    //lng: "ko",
    // ns: ['translation'],
    // defaultNS: "translation",
    debug: true,

    keySeparator: false, // we do not use keys in form messages.welcome
    interpolation: {
      escapeValue: false, // react already safes from xss
    },
  });

export default i18n;

答案 1 :(得分:0)

游戏进行得有点晚了,但希望能使社区受益。我最近开始与react-i18next合作,也遇到了这个问题。我发现此post的子链接指向源代码中的这一行:

https://github.com/i18next/i18next/blob/ee3afd8e5d958e8d703a208194e59fa5228165fd/src/i18next.js#L189

if (!lng && this.services.languageDetector) lng = this.services.languageDetector.detect();

这表明,如果不带任何参数调用changeLanguage(),它将尝试根据您配置的优先级进行语言检测。因此,要使其正常工作,请执行以下操作:

i18n
  .use(LanguageDetector)
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",
    detection: detectOptions,
    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

//*** call without param to use language detector
i18n.changeLanguage()

完成此操作后,URL查询参数现在可以使用,例如:

www.example.com/route/?lng=tr

答案 2 :(得分:0)

希望这对以后的人有所帮助。我在上面尝试了@Ergin的答案,但是没有用,当我使用此建议时,Typescript在传递0 params时引发错误:

//*** call without param to use language detector
i18n.changeLanguage()

文档并没有完全为您提供有关如何设置检测的全部信息,然后我发现一个closed Github issue,那里有几个人在问一个合理的问题,维护人员的回答有些粗鲁,但是还碰巧提供了本应包含在文档中的link。通过对当前文档的说明进行一些细微调整,它解决了我的问题。

然后,我可以使用https:www.domain.com?lng=es在我的网址中进行语言检测,并且可以使用浏览器扩展程序来更改浏览器语言。

这里有我的i18n.ts工作文件:

import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'
import XHR from "i18next-http-backend" // <---- add this

import commonDe from './locales/de/common.json'
import commonEn from './locales/en/common.json'
import commonEs from './locales/es/common.json'
import commonFr from './locales/fr/common.json'

const resources = {
  de: { common: commonDe },
  en: { common: commonEn },
  es: { common: commonEs },
  fr: { common: commonFr }
}

const options = {
  order: ['querystring', 'navigator'],
  lookupQuerystring: 'lng'
}

i18n
  .use(XHR) // <---- add this
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    // lng: 'en' // <--- turn off for detection to work
    detection: options,
    resources,
    ns: ['common'],
    defaultNS: 'common',
    fallbackLng: 'en',
    supportedLngs: ['de', 'en', 'es', 'fr'],
    interpolation: {
      escapeValue: false,
    },
    debug: false,
  })

export default i18n

(额外的帮助-如果有人在此部分卡住)

我正在一个Next.js项目中,并且上面的文件像这样被加载到project-root/pages/_app.tsx文件中:

import React from 'react'
import { AppProps } from 'next/app'
import '../i18n/i18n'

import '../public/styles.css'

const TacoFridayApp = ({ Component, pageProps}: AppProps): JSX.Element => {
  
  return <Component {...pageProps} />
}

export default TacoFridayApp