Next.js 13中如何让Layout内组件接收多语言路由参数
解决Layout中SideComponent无法获取lng参数的问题
核心问题
你的SideComponent无法获取lng参数,是因为组件不会自动继承父组件的params,必须手动传递。另外,SideComponent中useTranslation的使用方式需结合组件类型调整。
步骤1:在Layout中手动传递lng参数
修改app/[lng]/Layout.js,将lng参数主动传递给SideComponent:
import { dir } from 'i18next' import { languages } from '../i18n/settings' import SideComponent from "../../comp/component" export async function generateStaticParams() { return languages.map((lng) => ({ lng })) } export default function RootLayout({ children, params: { lng } }) { return ( <html lang={lng} dir={dir(lng)}> <head /> <body style={{display:"flex"}}> {/* 手动传入lng参数 */} <SideComponent lng={lng} /> {children} </body> </html> ) }
步骤2:调整SideComponent接收参数并修正翻译逻辑
根据组件类型(Server/Client)调整comp/component.js:
情况1:SideComponent是Server Component
如果是Server Component,直接接收lng参数,使用服务器端翻译方法(根据你的i18n库调整):
// 导入对应服务器端翻译工具,示例用next-intl import { getTranslations } from 'next-intl/server' export default async function SideComponent({ lng }) { // 服务器端获取翻译函数 const t = await getTranslations({ locale: lng, namespace: 'second-page' }) return ( <div> Hello sidebar {t('back-to-home')} </div> ) }
情况2:SideComponent是Client Component
如果是Client Component,需添加'use client'指令,使用客户端hook且不能用async/await:
'use client' import React from 'react' import { useTranslation, i18n } from 'react-i18next' export default function SideComponent({ lng }) { const { t } = useTranslation('second-page') // 监听lng变化切换语言 React.useEffect(() => { i18n.changeLanguage(lng) }, [lng]) return ( <div> Hello sidebar {t('back-to-home')} </div> ) }
额外注意事项
- 确保你的i18n配置支持对应组件类型的翻译逻辑(Server/Client)。
- 使用
generateStaticParams时,所有语言版本的静态页面会自动生成,传递lng后SideComponent会随对应语言版本渲染。
内容的提问来源于stack exchange,提问作者Keshav Tomar
相关产品推荐
相关产品推荐

