更改语言
如何更改你的 Next.js 应用的语言
概述
在本指南中,我们将向您展示如何更改 Next.js 应用程序的语言。
如果您尚未使用 gt-next
设置您的应用程序,请在继续之前参考快速入门指南。
使用 gt-next
更改应用程序语言有三种方法。
- 使用
useSetLocale()
hook - 使用
<LocaleSelector>
组件 - 使用
useLocaleSelector()
hook - 使用中间件 i18n 路由
我们将在本指南中介绍前三种方法。有关如何使用中间件更改应用程序语言的更多信息,请参阅中间件路由指南。
使用 useSetLocale
hook
useSetLocale
hook 是一个客户端 hook,允许您更改应用程序的语言。它必须在 GTProvider
组件内使用。
} from 'gt-next/client';
export default function MyComponent() {
const setLocale = useSetLocale();
return <button onClick={() => setLocale('en')}>Set Locale</button>;
}
只需将您想要更改到的语言环境作为参数提供给 useSetLocale
hook 返回的回调函数即可。
使用 <LocaleSelector>
组件
<LocaleSelector>
组件是一个客户端组件,可以让你切换应用的语言。它必须在 GTProvider
组件内部使用。
这是一个极简的 UI 下拉菜单,会显示你在项目中启用的所有语言区域,并允许用户选择不同的语言区域。
import { LocaleSelector } from 'gt-next/client';
export default function MyComponent() {
return <LocaleSelector />;
}
使用 useLocaleSelector
hook
或者,如果您想创建自己的语言选择器组件,可以使用 useLocaleSelector
hook。
此 hook 返回当前语言环境、项目支持的语言环境列表以及 useSetLocale
hook。
以下是如何使用 useLocaleSelector
hook 创建自定义语言选择器组件的示例。
import { useLocaleSelector, useGTClass } from 'gt-next/client';
function capitalizeLanguageName(language: string): string {
if (!language) return '';
return (
language.charAt(0).toUpperCase() +
(language.length > 1 ? language.slice(1) : '')
);
}
export default function LocaleDropdown({ className }: { className?: string }) {
// Retrieve the locale, locales, and setLocale function
const { locale, locales, setLocale, getLocaleProperties } = useLocaleSelector();
// Helper function to get the display name of a locale
const getDisplayName = (locale: string) => {
return capitalizeLanguageName(
getLocaleProperties(locale).nativeNameWithRegionCode
);
};
// If no locales are returned, just render nothing or handle gracefully
if (!locales || locales.length === 0 || !setLocale) {
return null;
}
return (
<Select onValueChange={setLocale} defaultValue={locale}>
<SelectTrigger>
<SelectValue placeholder='Select language' />
</SelectTrigger>
<SelectContent className='z-[200!important]' position='popper'>
<SelectGroup>
{!locale && <SelectItem value='' />}
{locales.map((locale) => (
<SelectItem key={locale} value={locale} suppressHydrationWarning>
{getDisplayName(locale)}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
);
}
查看 API 参考 了解更多信息。
后续步骤
- 进一步了解
useSetLocale
钩子。 - 进一步了解
<LocaleSelector>
组件。 - 进一步了解
useLocaleSelector
钩子。 - 进一步了解 中间件 i18n 路由。
这份指南怎么样?