Как перевести длинный текст длинный текст, используя react-i18next?

#reactjs #localization #react-i18next #i18next-browser-languagedetector

Вопрос:

парни. Я пытаюсь реализовать локализацию с помощью i18n для перевода моего веб-сайта. Я прочитал документы и посмотрел несколько учебников, но они сосредоточены только на одном файле с небольшой строкой, и я задался вопросом, как я мог бы перевести целый абзац ?

Вот ссылка на codesandbox с аналогичным описанием моего проекта: https://codesandbox.io/s/try-translating-long-texts-v0jdu?file=/src/App.jsx

Спасибо вам за ваше время и за вашу помощь. =D

Комментарии:

1. Нет ограничений на размер строк, которые вы можете поместить в файл перевода, поэтому я не уверен, в чем проблема с переводом абзаца. Не могли бы вы пояснить, что вас смущает?

Ответ №1:

Вы должны использовать файл JSON/JS с вашими переводами внутри.

Пример :

data.js

 const data = {
  /************ ENGLISH **************/
  en: {
    paragraph: `Bernard, as "custodian" of the "savage" John who is now treated as a celebrity, is fawned on by the highest members of society and revels in attention he once scorned. Bernard's popularity is fleeting, though, and he becomes envious that John only really bonds with the literary-minded Helmholtz. Considered hideous and friendless, Linda spends all her time using soma, while John refuses to attend social events organised by Bernard, appalled by what he perceives to be an empty society. Lenina and John are physically attracted to each other, but John's view of courtship and romance, based on Shakespeare's writings, is utterly incompatible with Lenina's freewheeling attitude to sex. She tries to seduce him, but he attacks her, before suddenly being informed that his mother is on her deathbed. He rushes to Linda's bedside, causing a scandal, as this is not the "correct" attitude to death. Some children who enter the ward for "death-conditioning" come across as disrespectful to John until he attacks one physically. He then tries to break up a distribution of soma to a lower-caste group, telling them that he is freeing them. Helmholtz and Bernard rush in to stop the ensuing riot, which the police quell by spraying soma vapor into the crowd.`,
  },
  /************ FRENCH **************/
  fr: {
    paragraph: `Bernard, en tant que "gardien" du "sauvage" John qui est maintenant traité comme une célébrité, est admiré par les plus hauts membres de la société et se délecte de l'attention qu'il a autrefois méprisée. La popularité de Bernard est éphémère, cependant, et il devient envieux que John ne se lie vraiment qu'avec le Helmholtz à l'esprit littéraire. Considérée comme hideuse et sans amis, Linda passe tout son temps à utiliser le soma, tandis que John refuse d'assister aux événements sociaux organisés par Bernard, consterné par ce qu'il perçoit comme une société vide. Lenina et John sont physiquement attirés l'un par l'autre, mais la vision de la cour et de la romance de John, basée sur les écrits de Shakespeare, est totalement incompatible avec l'attitude de Lenina à l'égard du sexe. Elle essaie de le séduire, mais il l'attaque, avant d'être soudainement informé que sa mère est sur son lit de mort. Il se précipite au chevet de Linda, provoquant un scandale, car ce n'est pas l'attitude "correcte" face à la mort. Certains enfants qui entrent dans la salle pour « conditionnement à mort » semblent irrespectueux envers John jusqu'à ce qu'il en attaque un physiquement. Il essaie ensuite de briser une distribution de soma à un groupe de caste inférieure, leur disant qu'il les libère. Helmholtz et Bernard se précipitent pour arrêter l'émeute qui s'ensuit, que la police réprime en pulvérisant de la vapeur de soma dans la foule.`,
  },
};

export default data;
 

Затем импортируйте его в свой файл i18n

i18n.js

 import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';

// Data
import data from './data';

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    // init data
    resources: {
      fr: {
        translation: data.fr,
      },
      en: {
        translation: data.en,
      },
    },
    fallbackLng: 'en',
    debug: false,
    ns: ['translations'],
    defaultNS: 'translations',
    keySeparator: false,
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;
 

Полная демонстрация : Stackblitz