【问题标题】:react-i18next translation is not working for passed on Prop elementsreact-i18next 翻译不适用于传递的 Prop 元素
【发布时间】:2023-03-26 04:11:01
【问题描述】:

我在我的项目中设置了一个 i18 翻译器,虽然它对项目中的其他元素工作正常,但它似乎不适用于传递的 prop 元素。

这就是我使用 i18 的方式:

import { useTranslation } from 'react-i18next';
const { t } = useTranslation();

//Using the translations
{t('kitchenware')} // <-- Working fine
{t(product?.name)} // <-- Error here
name={t(product.name)} // <-- No error, but translations doesn't seem to work

这是我收到的错误消息:

src/pages/product/index.tsx:48:33
TS2769: No overload matches this call.
  Overload 1 of 2, '(key: string | TemplateStringsArray | (string | TemplateStringsArray)[], options?: string | TOptions<StringMap> | undefined): TFunctionResult', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string | TemplateStringsArray | (string | TemplateStringsArray)[]'.
      Type 'undefined' is not assignable to type 'string | TemplateStringsArray | (string | TemplateStringsArray)[]'.
  Overload 2 of 2, '(key: string | TemplateStringsArray | (string | TemplateStringsArray)[], defaultValue?: string | undefined, options?: string | TOptions<StringMap> | undefined): TFunctionResult', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string | TemplateStringsArray | (string | TemplateStringsArray)[]'.

我将确保始终传递一个产品值,而不是 undefined 或 null。

【问题讨论】:

  • 这可能是因为如果 TypeScript... product?.name as string 可能有效?
  • 没有得到这个抱歉。
  • 尝试 console.log(product.name).... 输出的键是否正确?
  • 好的去试试
  • 是的,这是一个正确的密钥,这会按预期产生正确的输出。

标签: reactjs typescript i18next react-i18next


【解决方案1】:

我错误地引用了 i18 脚本。在正确的参考之后,这已经奏效了。

【讨论】: