[英]React components in i18next interpolation display as [object Object]
My React app uses next-i18next
package.我的 React 应用程序使用
next-i18next
package。 I'd like to put some React component inside my interpolation:我想在我的插值中加入一些 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']),
}
});
And reviews.json
:和
reviews.json
:
{
"footer": "By {{author}}, all rights reserved"
}
Trying to use JSX element to fill the interpolation doesn't work as expected.尝试使用 JSX 元素填充插值无法按预期工作。 The result I'm getting is:
我得到的结果是:
By [object Object], all rights reserved
作者:[object Object],保留所有权利
I also tried with unescaped interpolation with By {{- author}}, all rights reserved
, but it ends up being the same result.我还尝试使用
By {{- author}}, all rights reserved
,但结果相同。
Can I use JSX element to fill my interpolation?我可以使用 JSX 元素来填充我的插值吗?
You can't use t
function in order to inject jsx
.您不能使用
t
function 来注入jsx
。
There is a special Trans
component for this, you should use it.为此有一个特殊的
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'])),
},
});
When in your translation file you will have:在您的翻译文件中,您将拥有:
{
"footer": "My footer text <authorLink>{{author.name}}</authorLink>"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.