remix-i18n
v2.0.0
Published
[英文文档](./README.md)
Maintainers
Readme
Remix I18n
概述
Remix I18n 是一个为 Remix 应用程序设计的国际化库,提供简单易用的 API 来处理多语言支持、翻译和语言切换。
安装
npm install @your-org/remix-i18n
# 或
yarn add @your-org/remix-i18n
# 或
pnpm add @your-org/remix-i18n快速开始
1. 初始化 I18n 实例
// app/i18n.ts
import { RemixI18n } from '@your-org/remix-i18n';
export const i18n = new RemixI18n({
supportedLanguages: ['en', 'zh', 'es'],
fallbackLng: 'en',
});
// 设置翻译
const enTranslations = {
greeting: 'Hello, {{name}}!',
welcome: 'Welcome to our application',
menu: {
home: 'Home',
about: 'About',
contact: 'Contact',
},
};
const zhTranslations = {
greeting: '你好,{{name}}!',
welcome: '欢迎使用我们的应用',
menu: {
home: '首页',
about: '关于我们',
contact: '联系我们',
},
};
i18n.set('en', enTranslations);
i18n.set('zh', zhTranslations);2. 在根组件中提供 I18n 上下文
// app/root.tsx
import { I18nProvider } from '@your-org/remix-i18n';
import { i18n } from './i18n';
export default function App() {
return (
<I18nProvider i18n={i18n}>
<Outlet />
</I18nProvider>
);
}3. 在组件中使用翻译
// app/routes/index.tsx
import { useI18n } from '@your-org/remix-i18n';
export default function Home() {
const i18n = useI18n();
return (
<div>
<h1>{i18n.t('welcome')}</h1>
<p>{i18n.t('greeting', { name: 'John' })}</p>
<nav>
<ul>
<li>{i18n.t('menu.home')}</li>
<li>{i18n.t('menu.about')}</li>
<li>{i18n.t('menu.contact')}</li>
</ul>
</nav>
</div>
);
}4. 切换语言
// app/routes/settings.tsx
import { useI18n } from '@your-org/remix-i18n';
export default function Settings() {
const i18n = useI18n();
const handleLanguageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
i18n.locale(e.target.value);
};
return (
<div>
<h2>设置</h2>
<select value={i18n.locale()} onChange={handleLanguageChange}>
<option value="en">English</option>
<option value="zh">中文</option>
<option value="es">Español</option>
</select>
</div>
);
}API 文档
RemixI18n 类
构造函数
new RemixI18n(options: RemixI18nOptions)参数
supportedLanguages: 支持的语言列表fallbackLng: 回退语言
方法
locale(lang?: string): string获取或设置当前语言set(lang: string, dict: I18nDict): void设置指定语言的翻译字典t(key: string, params?: any, lang?: string): string获取翻译,支持参数替换setOnChange(fn: (locale: string) => void): void设置语言变化时的回调函数
组件和钩子
I18nProvider组件 提供 I18n 上下文useI18n()钩子 获取 I18n 实例
赞助
维护者: Willin Wang
如果您对本项目感兴趣,可以通过以下方式支持我:
许可证
Apache-2.0
