You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向i18next的useTranslation钩子的t函数传递两个参数?

在i18next中获取多个翻译值的正确方式

首先要纠正一个细节:你的翻译文件里cat和dog嵌套在foo对象下,规范的翻译键应该是foo.cat和foo.dog——之前调用t('cat')能返回结果可能是因为i18next配置有特殊处理,但建议使用完整路径避免歧义。

回到你的需求:i18next的t函数不支持直接传入两个翻译键来同时返回两个结果,第二个参数的作用是传递选项(比如插值参数、默认值、命名空间等),不是第二个翻译键。你之前调用t('cat', 'dog')时,'dog'被当作cat键不存在时的默认值,但因为cat键有效,所以只返回了Cat。

要获取多个翻译值,有几种实用方法:

方法一:分别调用t函数

直接对每个翻译键单独调用t函数:

const { t } = useTranslation();
const catText = t('foo.cat');
const dogText = t('foo.dog');

// 组合使用示例
console.log(`${catText} and ${dogText}`); // 输出 "Cat and Dog"

方法二:定义组合翻译键

如果需要固定组合的文本,可以在翻译文件里直接定义组合后的键:

// translation_en.js
foo: {
    cat: 'Cat',
    dog: 'Dog',
    catAndDog: 'Cat and Dog'
}

调用时直接使用组合键:

t('foo.catAndDog'); // 返回 "Cat and Dog"

方法三:使用插值动态组合

如果需要动态替换组合里的内容,可以用i18next的插值功能:

// translation_en.js
foo: {
    cat: 'Cat',
    dog: 'Dog',
    twoAnimals: '{{animal1}} and {{animal2}}'
}

调用时传入插值参数:

t('foo.twoAnimals', { 
    animal1: t('foo.cat'), 
    animal2: t('foo.dog') 
}); // 返回 "Cat and Dog"

内容的提问来源于stack exchange,提问作者four-eyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:57:27