JGuang

国际化

InternationalizationProvider · Astryx

交互预览
npm install @astryxdesign/core@0.7.1 @astryxdesign/theme-neutral@0.7.1 @stylexjs/stylex@0.19.0

国际化 · InternationalizationProvider

设置本地化消息、语言与文本方向。

安装与前置条件

npm install @astryxdesign/core@0.7.1 @astryxdesign/theme-neutral@0.7.1 @stylexjs/stylex@0.19.0

需要 React 19+,按顺序导入基础 CSS 和主题,并设置 Theme Provider。参见开始使用。

示例与使用方式

  • 国际化 · 交互示例 1:首先体验这个示例,再查看代码理解组件的组合方式。
  • 国际化 · 交互示例 2:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。
  • 国际化 · 交互示例 3:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。

API 与上游详细参考

优先使用 0.7.1 官方中文说明;上游尚未提供中文的条目保留英文。属性名、类型及默认值保持原生 API,不把示例状态名称当成组件属性。

Internationalization Provider

Wraps your app to set the active locale and (optionally) merge additional translation catalogs + per-locale overrides. Astryx components inside the subtree resolve their strings against this context. If no provider is present, components fall back to the shipped English defaults.

属性类型默认值说明
locale *stringBCP 47 language tag for the active locale (e.g. "en", "pt", "pt-BR", "zh-Hans"). Regional tags fall back to their base language, then to the shipped "en" catalog.
messagesProviderMessagesByLocaleOptional map of BCP 47 tag to a rich or generated runtime catalog. Import compact shipped catalogs from @astryxdesign/core/locales/*.generated.js; the shipped "en" catalog is always available and does not need to be listed here.
overridesOverridesSparse per-locale key overrides applied on top of shipped defaults. Overrides are locale-keyed so a runtime locale swap picks up the correct set.
dir'ltr' | 'rtl'Explicit text-direction override for the context. When omitted, direction is derived from locale via Intl.Locale.getTextInfo(). This sets the direction Astryx reads, but it does NOT set the DOM dir attribute; you must set dir on <html> (or a wrapping element) yourself, since Astryx components mirror layout and directional icons from the DOM dir, not from this prop. Set both to the same value and keep them in sync.
children *ReactNodeContent to render with the internationalization provider.

使用建议

  • Use shipped Astryx locale catalogs from @astryxdesign/core/locales/* when one exists for your target locale.
  • Use a same-shape local catalog only when Astryx has not shipped that locale yet or you are testing in-progress translations.
  • Use real BCP 47 tags such as fr-FR, pt-BR, or ar-SA; regional locales fall back to their base language before English.
  • Set the dir attribute on <html> (or a wrapping element) yourself; the provider does not set it. Astryx components mirror layout and directional icons from the DOM dir, so an RTL locale won't visually mirror without it. Use getLocaleDirection(locale) to derive the value for both the provider and the DOM.
  • 避免:Cast custom catalog maps to any; the i18n package exports ProviderMessagesByLocale, MessagesByLocale, Catalog, and RuntimeCatalog for local catalog typing.

Load a shipped Astryx locale catalog

import type {ReactNode} from 'react';
import {InternationalizationProvider} from '@astryxdesign/core/i18n';
import frFR from '@astryxdesign/core/locales/fr-FR.generated.js';

export function AppI18n({children}: {children: ReactNode}) {
  return (
    <InternationalizationProvider locale="fr-FR" messages={{'fr-FR': frFR}}>
      {children}
    </InternationalizationProvider>
  );
}

Override one Astryx string

import type {ReactNode} from 'react';
import {InternationalizationProvider} from '@astryxdesign/core/i18n';

export function AppI18n({children}: {children: ReactNode}) {
  return (
    <InternationalizationProvider
      locale="en"
      overrides={{
        en: {'@astryx.selector.placeholder': 'Choose...'},
      }}
    >
      {children}
    </InternationalizationProvider>
  );
}

Provide a local fallback catalog

import type {ReactNode} from 'react';
import {
  InternationalizationProvider,
  type MessagesByLocale,
} from '@astryxdesign/core/i18n';
import ptBR from './locales/pt-BR.json';

const messages: MessagesByLocale = {'pt-BR': ptBR};

export function AppI18n({children}: {children: ReactNode}) {
  return (
    <InternationalizationProvider locale="pt-BR" messages={messages}>
      {children}
    </InternationalizationProvider>
  );
}

useCollator

Returns the sanctioned locale-aware comparator for custom sorting. The collator is recreated when the provider locale or an option changes.

Parameters

ParameterTypeDescription
optionsIntl.CollatorOptionsOptional collation behavior such as numeric ordering, sensitivity, punctuation handling, and case order.

Returns

[
  {
    "name": "collator",
    "type": "Intl.Collator",
    "description": "A memoized collator bound to the active InternationalizationProvider locale."
  }
]

使用建议

  • Reuse collator.compare in custom Table comparators and other user-visible string ordering.
  • 避免:Construct Intl.Collator directly or call localeCompare; those bypass the provider-backed locale contract.

useLocale

Reads the authoritative Astryx locale. Use it to thread the provider locale into pure formatting helpers and sibling-package APIs; do not derive a second locale from navigator.language or a hardcoded literal.

Returns

[
  {
    "name": "locale",
    "type": "Locale",
    "description": "The active InternationalizationProvider BCP 47 locale. Falls back to 'en' when no provider is present."
  }
]

使用建议

  • Pass the returned locale to pure Astryx helpers or package APIs that require an explicit locale.
  • 避免:Use navigator.language or a hardcoded display locale as a fallback; InternationalizationProvider is the locale source.

useTranslator

Returns a translator function that resolves keys against the current locale, provider overrides, and the shipped English fallback catalog. Call inside a component; the returned function can be used anywhere within that component's scope.

Returns

[
  {
    "name": "value",
    "type": "(key: string, values?: Record<string, string | number | Date>) => string",
    "description": "A stable translator function bound to the current InternationalizationProvider context. Call it with a message key and optional ICU MessageFormat values to get the formatted string in the active locale. Safe to use in render, event handlers, effects, or any code that runs during the parent component's lifecycle."
  }
]