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

Tom*_*más 9 reactjs next.js13

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

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

\n
export default function DashboardMenu(){\n    const lang: DashboardLangsTypes = getLang("en", "dashboard"); // i want the lang here\n    return (\n...\n
Run Code Online (Sandbox Code Playgroud)\n

小智 1

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

  const router = useRouter();
  const lang = router.query.lang;
Run Code Online (Sandbox Code Playgroud)

导入它:

import { useRouter } from "next/router";
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

import { useRouter } from "next/router";

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

  return (
    ....
  );
}
Run Code Online (Sandbox Code Playgroud)