i18next 插值中的 React 组件显示为 [object Object]

问题描述 投票:0回答:2

我的 React 应用程序使用

next-i18next
包。我想在我的插值中放入一些 React 组件:

import React from 'react';
import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

export default function Review({ text, author }) {
  const { t } = useTranslation('reviews');

  return (
    <article>
      <p>{text}</p>
      <footer>
        {t('footer', { author: <a href={author.url}>{author.name}</a> })}
      </footer>
    </article>
  );
}

export const getStaticProps = async ({ locale }) => ({
  props: {
    ...await serverSideTranslations(locale, ['reviews']),
  }
});

reviews.json

{
    "footer": "By {{author}}, all rights reserved"
}

尝试使用 JSX 元素来填充插值无法按预期工作。我得到的结果是:

作者:[object Object],保留所有权利

我也尝试过使用

By {{- author}}, all rights reserved
进行非转义插值,但最终得到相同的结果。

我可以使用 JSX 元素来填充我的插值吗?

javascript reactjs i18next react-i18next next-i18next
2个回答
6
投票

您不能使用

t
函数来注入
jsx

有一个特殊的

Trans
组件,你应该使用它。

import React from 'react';
import { useTranslation, Trans } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

export default function Review({ text, author }) {
  const { t } = useTranslation('reviews');

  return (
    <article>
      <p>{text}</p>
      <footer>
        <Trans
          i18nKey="footer"
          t={t}
          values={{ author }}
          components={{ authorLink: <a href={author.url}>placeholder</a> }}
        />
      </footer>
    </article>
  );
}

export const getStaticProps = async ({ locale }) => ({
  props: {
    ...(await serverSideTranslations(locale, ['reviews'])),
  },
});

在您的翻译文件中,您将拥有:

{
  "footer": "My footer text <authorLink>{{author.name}}</authorLink>"
}

0
投票

嘿,您是否设法解决了这个问题,或者找到了解决方法?我将非常感激。

我正在将旧的 React 应用程序(需要保持不变)重写为新的 next.js 项目,并且需要在两者中使用翻译文件。然而,旧的以

{{var}}
语法插入组件,所以我无法更改我的翻译文件。

© www.soinside.com 2019 - 2024. All rights reserved.