gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:39:23 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com