Helpers
useLocaleSelector()
useLocaleSelector 钩子的 API 参考
概述
此 hook 返回当前的语言环境、语言环境列表,以及 useSetLocale()
hook。
这旨在方便你创建自己的语言选择器组件时使用。
如果你不想自己实现,也可以直接使用 <LocaleSelector>
组件。
参考
返回值
一个对象,包含当前的语言环境、语言环境列表,以及 useSetLocale()
钩子。
示例
<LocaleSelector>
这是 <LocaleSelector>
组件的示例实现。
export default function LocaleSelector({
locales: _locales,
...props
}: {
locales?: string[];
[key: string]: any;
}): React.JSX.Element | null {
// Get locale selector properties
const { locale, locales, setLocale, getLocaleProperties } = useLocaleSelector(
_locales ? _locales : undefined
);
// Get display name
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
{...props}
// Fallback to an empty string if currentLocale is undefined
value={locale || ''}
onChange={(e) => setLocale(e.target.value)}
>
{/* Optional fallback for when no locale is set */}
{!locale && <option value='' />}
{locales.map((locale) => (
<option key={locale} value={locale} suppressHydrationWarning>
{getDisplayName(locale)}
</option>
))}
</select>
);
}
注意事项
- 该 hook 仅限于客户端使用。
- 在此处了解更多关于 locale strings 的信息。
后续步骤
- 进一步了解
<LocaleSelector>
组件。 - 进一步了解
useLocale()
钩子。
这份指南怎么样?