我的 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 元素填充插值无法按预期工作。我得到的结果是:By [object Object], all rights reserved
我还尝试使用
By {{- author}}, all rights reserved
进行未转义插值,但最终结果相同。我可以使用 JSX 元素来填充我的插值吗?
最佳答案
您不能使用 t
函数以注入(inject) jsx
.
有一个特殊的 Trans
component为此,您应该使用它。
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>"
}
关于javascript - i18next 插值中的 React 组件显示为 [object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66754955/