reactjs 从Next.JS 13中的布局或组件文件访问搜索参数

0yg35tkg  于 2023-03-29  发布在  React
关注(0)|答案(2)|浏览(86)

我想访问组件或布局文件中的搜索参数以获取lang。有一种方法可以做到这一点吗?我读到不可能在布局文件中获取searchparams,但在Next.JS 13中有任何其他方法吗?或者其他方法可以在组件中获取lang?

export default function DashboardLayout({ children }: DashboardProps) {
    return (
        <html>
            <body>
                <div className="w-full h-full flex absolute bg-slate-100">
                    <div className="flex flex-col">
                        <div className="bg-sky-800 w-[20rem] h-12 flex items-center justify-center">
                            <img src="/bigLogo.svg" className="w-28 h-12" title="ProPay" alt="ProPay" />
                        </div>
                        <div className="bg-white h-full shadow-md">
                            <DashboardMenu />
                        </div>
                    </div>
                    <div className="flex flex-col w-full">
                        <div className="bg-sky-700 flex justify-between items-center h-12 pr-5">
                            <p className="ml-5 text-lg text-white">Câmara Municipal de Tondela</p>
                            <SelectLang />
                        </div>
                        <div className="p-3">
                            {children}
                        </div>
                    </div>
                </div>
            </body>
        </html>
    )
};

.

export default function DashboardMenu(){
    const lang: DashboardLangsTypes = getLang("en", "dashboard"); // i want the lang here
    return (
...
fhg3lkii

fhg3lkii1#

你可以使用router获取lang作为参数,然后将其作为props传递给你的组件

const router = useRouter();
  const lang = router.query.lang;

要导入,请执行以下操作:

import { useRouter } from "next/router";

在您情况下:

import { useRouter } from "next/router";

export default function DashboardLayout({ children }: DashboardProps) {
  const router = useRouter();
  const lang = router.query.lang;

  return (
    ....
  );
}
hmmo2u0o

hmmo2u0o2#

由于您使用的是服务器组件,因此可以将next/router的用法替换为next/navigation

import { useNavigation } from "next/navigation";

export default function DashboardLayout({ children }: DashboardProps) {
  const navigation = useNavigation();
  const lang = navigation.searchParams.get('lang');

  return (
    ....
  );
}

相关问题