React i18n,如何插入字符串(即不使用 <Trans> 组件)?

React i18n, how to interpolate to a string (i.e. without using <Trans> component)?

我的 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组件。

您可以直接使用i18n服务:

// import it
import i18n from "i18next";

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

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