Helpers

useLocaleSelector()

useLocaleSelector 钩子的 API 参考

概述

这个钩子返回当前语言环境、语言环境列表以及 useSetLocale() 钩子。 这是为了在创建自己的语言环境选择器组件时方便使用。

如果你不想实现自己的选择器,你可以使用 <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 } = 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>
  );
}

注意事项

  • 此钩子仅限客户端使用。
  • 了解更多关于区域设置字符串的信息点击这里

后续步骤

在本页面