更改语言

如何更改你的 React 应用的语言

概述

在本指南中,我们将向你展示如何更改你的 React 应用的语言。

如果你还没有使用 gt-react 设置你的应用,请在继续之前参考快速入门指南

你可以通过三种方式使用 gt-react 更改应用的语言。

  1. 使用 useSetLocale() hook
  2. 使用 <LocaleSelector> 组件
  3. 使用 useLocaleSelector() hook

我们将在本指南中介绍这三种方法。

使用 useSetLocale 钩子

useSetLocale 钩子是一个客户端钩子,允许你更改应用的语言。它必须在 GTProvider 组件内部使用。

import { useSetLocale } from 'gt-react';
export default function MyComponent() {
  const setLocale = useSetLocale();

  return <button onClick={() => setLocale('en')}>Set Locale</button>;
}

只需将你想要切换到的语言作为参数传递给 useSetLocale 钩子返回的回调函数即可。

使用 <LocaleSelector> 组件

<LocaleSelector> 组件是一个客户端组件,允许你更改应用的语言。它必须在 GTProvider 组件内部使用。

这是一个极简的 UI 下拉菜单,会显示你在项目中启用的所有语言选项,并允许用户选择不同的语言环境。

import { LocaleSelector } from 'gt-react';

export default function MyComponent() {
  return <LocaleSelector />;
}

使用 useLocaleSelector hook

或者,如果您想创建自己的语言选择器组件,可以使用 useLocaleSelector hook。

此 hook 返回当前语言环境、项目支持的语言环境列表以及 useSetLocale hook。

以下是如何使用 useLocaleSelector hook 创建自定义语言选择器组件的示例。

import { useLocaleSelector } from 'gt-react';

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 参考 了解更多信息。

后续步骤

这份指南怎么样?