Rob*_*bok 5 javascript i18next reactjs react-i18next next-i18next
我的 React 应用程序使用next-i18nextpackage.json。我想在我的插值中放入一些 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']),
}
});
Run Code Online (Sandbox Code Playgroud)
和reviews.json:
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']),
}
});
Run Code Online (Sandbox Code Playgroud)
尝试使用 JSX 元素来填充插值无法按预期工作。我得到的结果是:
作者:[object Object],保留所有权利
我还尝试使用 进行非转义插值By {{- author}}, all rights reserved,但最终得到相同的结果。
我可以使用 JSX 元素来填充我的插值吗?
您不能使用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'])),
},
});
Run Code Online (Sandbox Code Playgroud)
在您的翻译文件中,您将拥有:
{
"footer": "My footer text <authorLink>{{author.name}}</authorLink>"
}
Run Code Online (Sandbox Code Playgroud)