首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用转换将-i18下一个值传递到.json中

使用转换将-i18下一个值传递到.json中
EN

Stack Overflow用户
提问于 2022-05-09 00:57:19
回答 2查看 1.4K关注 0票数 1

我跟踪了这篇文章:https://dev.to/adrai/how-to-properly-internationalize-a-react-application-using-i18next-3hdb

现在,我想知道是否有方法将参数传递到从.json文件中提取的字符串中。

public/locales/en/transation.json

代码语言:javascript
复制
{
  "GREETING": "Hello ${name}, nice to see you."
}

src/i18n.ts

代码语言:javascript
复制
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';

i18n
  // i18next-http-backend
  // loads translations from your server
  // https://github.com/i18next/i18next-http-backend
  .use(Backend)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    debug: false,
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false // not needed for react as it escapes by default
    }
  });

export default i18n;

src/App

代码语言:javascript
复制
import React, {useState} from 'react';
import {useTranslation} from 'react-i18next';

function App() {
  const {t} = useTranslation();
  const [name] = useState('John Doe');

  return (
    <div>
      <p>{t('GREETING')}</p>
    </div>
  );
}

export default App;

当前:浏览器正在显示“Hello${name},很高兴见到您”。

我需要的:浏览器显示“你好,无名氏,很高兴见到你。”

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-09 05:44:45

默认情况下,i18next使用不同的格式前缀({{)和后缀(}})。

试着像这样写你的翻译:

代码语言:javascript
复制
{
  "GREETING": "Hello {{name}}, nice to see you."
}

内插变量如下所示:

代码语言:javascript
复制
<p>{t('GREETING', {name: "John Doe")}</p>
票数 4
EN

Stack Overflow用户

发布于 2022-05-09 02:55:25

您必须将变量作为第二个参数传递给"t“函数。

代码语言:javascript
复制
<p>{t('GREETING', {name: "John Doe")}</p>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72166063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档