前言
将 Next.js 的国际化 (i18n) 功能与 react-i18next 结合使用是一个常见的做法。您已经在项目中引入了 i18next 和 react-i18next,并且在 中配置了 Next.js 的 i18n 路由。
以下是如何将它们更好地结合起来的步骤和建议:
-
确保
i18next初始化正确:
您已经在 文件中初始化了i18n。这是一个很好的起点。请确保supportedLngs与 中的locales一致。// typescript:src/i18n.ts // ... existing code ... i18n.use(initReactI18next).init({ fallbackLng: 'en', // 确保与 next.config.ts 的 defaultLocale 一致或兼容 supportedLngs: ['en', 'zh'], // 确保与 next.config.ts 的 locales 一致 // lng: 'en', // 通常不需要在这里硬编码 lng,Next.js 的路由会处理当前语言 resources: { en: { translation: { welcome: 'Welcome', chat: 'Go to Chat', // ...更多英文翻译 }, }, zh: { translation: { welcome: '欢迎', chat: '进入聊天', // ...更多中文翻译 }, }, }, // interpolation: { // 如果需要,可以配置插值 // escapeValue: false, // }, // debug: process.env.NODE_ENV === 'development', // 开发模式下开启 debug }); // ... existing code ... -
在应用顶层提供
I18nextProvider:
为了让react-i18next的 hooks (如useTranslation) 能够在您的组件中使用,您需要在应用的根布局 () 中包裹您的children。首先,您可能需要创建一个客户端组件来包裹
I18nextProvider,因为i18n实例的传递通常在客户端进行。创建一个新的客户端组件,例如
src/components/I18nProviderWrapper.tsx:// typescript:src/components/I18nProviderWrapper.tsx 'use client' import { I18nextProvider } from 'react-i18next' import i18n from '@/i18n' // 确保路径正确 export default function I18nProviderWrapper({ children }: { children: React.ReactNode }) { return <I18nextProvider i18n={ i18n}>{ children}</I18nextProvider> }然后,在您的根布局 中使用它:
tsx:src/app/layout.tsx // ... existing code ... import I18nProviderWrapper from "@/components/I18nProviderWrapper"; // 导入包装器 // ... existing code ... export default function RootLayout({ children, params, // Next.js 13+ App Router 会传递 params,其中包含 locale }: Readonly<

最低0.47元/天 解锁文章
1552

被折叠的 条评论
为什么被折叠?



