首页 > 解决方案 > React i18n,如何插入字符串(即不使用零件)?

问题描述

我的 React 组件中有这个功能:

const fireError = (n) => {
   alert(`The value should go over ${n}% to be accepted.`);
}

在我的翻译 JSON 中,我有这个:

{ "percentage": "The value should go over {{percentage}} to be accepted" }

我怎样才能使这项工作?当然我不能使用 Trans 组件。

标签: javascriptreactjsi18nextreact-i18next

解决方案


您可以i18n直接使用该服务:

// import it
import i18n from "i18next";

// in your React component
const fireError = (n) => {
   alert(i18n.t('percentage', { percentage: n }));
}

请记住,在调用此函数之前必须初始化库 -i18n.init()必须已经被调用。


推荐阅读