实现效果 : 根据浏览器语言判断和手动切换(两种切换模式)
实现方法
1.下载安装包 (next-i18next react-i18next i18next)
yarn add next-i18next react-i18next i18next
2.在根目录下创建文件(next-i18next.config.js)
const path = require("path");
module.exports = {
i18n: {
defaultLocale: "zh",
locales: ["zh", "en"],
},
localePath: path.resolve("./public/locales"),
shallowRender: true,
};
3.修改文件(next.config.js)
/** @type {import('next').NextConfig} */
const { i18n } = require('./next-i18next.config')
const nextConfig = {
reactStrictMode: true,
i18n,
}
module.exports = nextConfig
4.public目录下编写文本
5.pages目录下的_app.tsx文件修改
import "@/styles/globals.css";
import type { AppProps } from "next/app";
import { appWithTranslation } from "next-i18next";
import nextI18NextConfig from "../../next-i18next.config";
function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
export default appWithTranslation(App, nextI18NextConfig);
6.页面中使用
import { useTranslation, I18nContext } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import nextI18NextConfig from "../../next-i18next.config.js";
import { useRouter } from "next/router.js";
import { Menu } from "antd";
export interface IndexProps {}
export default function Home(props: IndexProps) {
const langs = {
zh: "中国站",
en: "Intl English",
};
const router = useRouter();
const handleLanguageChange = (key: any) => {
console.log(key);
router.push(router.route, router.asPath, {
locale: key,
});
};
const { t } = useTranslation("common");
return (
<div>
{t("nav.footer.solutions")}
<Menu onClick={({ key }) => handleLanguageChange(key)}>
{Object.keys(langs).map((key) => (
<Menu.Item key={key}>{langs[key]}</Menu.Item>
))}
</Menu>
</div>
);
}
export const getStaticProps = async ({ locale }: any) => ({
props: {
...(await serverSideTranslations(locale, ["common"], nextI18NextConfig)),
},
});
(但是注意react13以上并且用的是app路由的话最好是并采取这种方案i18n with Next.js 13 and app directory / App Router (an i18next guide))