簡體   English   中英

i18next 插值中的 React 組件顯示為 [object Object]

[英]React components in i18next interpolation display as [object Object]

我的 React 應用程序使用next-i18next package。 我想在我的插值中加入一些 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 元素來填充我的插值嗎?

您不能使用t function 來注入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>"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM