如何用next-i18next实现NextJS单句多链接的国际化翻译?
NextJS 单句多链接国际化实现方案分享
需求背景
解决NextJS中包含3个不同链接的单句国际化翻译需求,让带多链接的句子能随语言环境正确渲染,同时链接的文本与跳转地址也支持国际化配置。
国际化资源文件配置
在/public/locales/en/common.json中定义带插槽的句子及对应链接信息:
// /public/locales/en/common.json { "multipleLink": { "label": "This is a <1>link</1>, a <2>link2</2> and a <3>third</3>", "links": { "link": { "label": "first link", "url": "/url-first-link" }, "link2": { "label": "second link", "url": "/url-second-link" }, "third": { "label": "third link", "url": "/url-third-link" } } } }
通过<1>``<2>``<3>标记句子中的链接插槽,每个插槽对应links对象里的配置项,包含国际化的链接文本和跳转地址。
原实现代码
以下是能满足需求但不够优雅的实现代码:
import { ReactNode, MouseEventHandler } from 'react'; import { Trans, useTranslation } from 'next-i18next'; // 最终渲染效果:"This is a first link, a second link and a third link" const MyComponent = () => { return ( <Trans i18nKey="multipleLink.label"> <MyLinkComponent>_</MyLinkComponent> <MyLinkComponent>_</MyLinkComponent> {/* 发现这个技巧最多能处理9个插槽,但局限性很大 */} <MyLinkComponent>_</MyLinkComponent> <MyLinkComponent>_</MyLinkComponent> <MyLinkComponent>_</MyLinkComponent> <MyLinkComponent>_</MyLinkComponent> <MyLinkComponent>_</MyLinkComponent> {/* 没完全搞懂这里的逻辑,但确实能用 */} <MyLinkComponent>_</MyLinkComponent> <MyLinkComponent>_</MyLinkComponent> </Trans> ) } /** * 处理链接的渲染与交互逻辑 */ interface MyLinkComponentProps { children: ReactNode; } const MyLinkComponent = ({ children }: MyLinkComponentProps) => { const { t } = useTranslation(); const handleClick: MouseEventHandler<HTMLAnchorElement> = () => { console.log(children); // 输出值为 'link' | 'link2' | 'third' }; return ( <a href={t(`multipleLink.links.${children}.url`)} onClick={handleClick}> {t(`multipleLink.links.${children}.label`)} </a> ); }
原方案存在的问题
- 需要冗余声明多个
<MyLinkComponent>才能覆盖插槽,代码臃肿且逻辑不直观 - 开发者未完全理解插槽匹配的底层逻辑,后续维护存在风险
说明
因未找到同类解决方案,特此分享这个可行但粗糙的实现。欢迎各位补充完善、优化现有逻辑,或提供更优雅的替代方案。
内容的提问来源于stack exchange,提问作者Paul Bompard
相关产品推荐
相关产品推荐

